Servlet是服务器上的一个Java程序,负责处理客户端发来的请求并向客户端发送响应内容,Servlet可以和URL形 成映射,客户端访问对应的URL就能执行Servlet中的功能了。
创建Servlet
1. 在src中创建 com.hyxy.servlet.TestServlet
public class TestServlet extends HttpServlet {
}
通过查看HttpServlet的源代码发现,HttpServlet是一个抽象类,定义了各种请求方式的处理方法,通过重写 这些方法实现自己的各种请求方式的处理过程;HttpServlet中包含了Service方法,处理所有的请求方式的方法;HttpServlet继承了GenericServlet类
GenericServlet类中实现了Servlet接口、ServletConfig接口、Serializable接口 ;GenericServlet类定义了 destroy方法(销毁方法),init方法(初始化方法),service抽象方法
Servlet接口中定义了 init、destroy、service抽象方法
ServletConfig接口中定义了getServletContext、getInitParameter抽象方法
//需求:
//浏览器访问 http://localhost:8080/web0529_war_exploded/hello
//在后台 打印Hello Servlet的输出
public class TestServlet extends HttpServlet {
//选择1 : 重写doGet方法 ,实现System.out.println
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Hello Servlet");
}
//选择2 : 重写service方法,实现ystem.out.println
}
//需求:
//浏览器访问 http://localhost:8080/web0529_war_exploded/hello
//在后台 打印Hello Servlet的输出
public class TestServlet extends HttpServlet {
//选择1 : 重写doGet方法 ,实现System.out.println
/* @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Hello Servlet");
}*/
//选择2 : 重写service方法,实现ystem.out.println
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Hello Servlet");
}
}
service方法和doXXX方法不能同时存在,否则只会执行service方法
2. 配置Servlet和地址的映射 ,通过web.xml配置文件完成配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 配置了一个Servlet -->
<servlet>
<!-- 为这个Servlet起一个名字,和Servlet类名无关,完全是自定义的 -->
<servlet-name>testServlet</servlet-name>
<!-- 配置Servlet的全类名(包名+类名) -->
<!-- 目地:让Web服务器(tomcat)通过反射自动创建Servlet对象 -->
<servlet-class>com.hyxy.servlet.TestServlet</servlet-class>
</servlet>
<!-- 为某个Servlet配置映射的地址 -->
<servlet-mapping>
<!-- 为这个Servlet配置映射地址 -->
<servlet-name>testServlet</servlet-name>
<!-- 映射的地址 -->
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
一个Servlet可以映射多个地址,但是一个地址不能映射多个Servlet
Servlet容器
tomcat用于存储、管理Servlet的一个容器,当客户端访问了Servlet映射的URL时,Servlet容器中如果没有Servlet 对象,由Servlet容器创建Servlet对象,并存储在Servlet容器中 ;如果Servlet容器中有这个对象,就不在创建 Servlet对象,Servlet容器保证了一个Servlet类在容器中只有一个Servlet对象 容器管理着Servlet对象的创建和销毁。Tomcat的Servlet容器名字叫Catalina
Servlet的生命周期方法
1. init方法:初始化方法,在Servlet对象被创建时,自动执行这个方法
2. destroy方法:销毁方法,在Servlet对象被销毁时,自动执行这个方法
3. service方法:处理请求的方法,当访问这个Servlet的URL时,自动执行这个方法
4. doGet/doPost方法:处理请求的方法
4749

被折叠的 条评论
为什么被折叠?



