欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Servlet执行流程和生命周期

程序员文章站 2022-06-03 08:38:34
...

慕课网学习而来:https://www.imooc.com/video/5550

流   程

客户端请求(就是在浏览器输入一个url)  

如 <a href="top/chgl16/servlet/MyServlet1">跳转</a>      

# url =  "top/chgl16/servlet/MyServlet1",top前加不加'/'都一样,毕竟前面还有主机名,比如localhost:8080/ , 但是<url-pattern>属性值的前面必须加'/',不然等着报错

服务器端会在web.xml文件(就是servlet类的注册文件)中找到相应的url

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <servlet>
    <servlet-name>myServlet1</servlet-name>
    <servlet-class>top.chgl16.servlet.MyServlet1</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>myServlet1</servlet-name>
    <url-pattern>/servlet/MyServlet1</url-pattern>
  </servlet-mapping>
</web-app>

也就是从<servlet-maping>入手,找到客户端请求的url(去掉主机名那部分),找到匹配的<url-pattern>属性,读取其<servlet-name>,然后通过<servlet-name>去<servlet>标签里面匹对,获取配对的<servlet-class>就是对应的后台servlet类了。

注:可以看到<servlet>和<servlet-mapping>优先检索<servlet-mapping>,两者中的子标签<servlet-name>可以随意写,但是要一致相同。<url-pattern>就是在浏览器运行这个servlet类的url,也可以随意任性写。但是还是规范好。

 

生命周期

1. 实例化,构造函数

2. 调用init()函数初始化

3. 客户端请求后调用service(req, resp)函数,根据请求方式去调用doGet(req, resp), doPsost(req, resp)

4. 调用doGet(req, resp)或者doPost(req, resp)方法

5. 服务器关闭后,调用销毁方法 destroy()

Servlet执行流程和生命周期

写了个类测试学习

package top.chgl16.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Lin 2018-5-31
 * 测试Servlet的生命周期
 */
public class MyServlet1 extends HttpServlet {
    public MyServlet1() {
        System.out.println("调用了Servlet的构造函数");
    }

    @Override
    public void init() {
        System.out.println("调用了init函数");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("调用service方法");
        doPost(req, resp);        // 这里指定了doPost,源码的service方法是根据客户端请求类型决定调用哪个的
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req, resp);
        System.out.println("调用了doGet方法");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("调用了doPost方法");
    }

    @Override
    public void destroy() {
        System.out.println("调用了destroy方法");
    }

}

注意:

1. 重载的service方法,指定了doPost,源码的service方法是根据客户端请求类型决定调用哪个的

2. 除了构造方法,每个方法的返回值都是空void

3. init, service, doGet, doPost的方法修饰符是protected,即子类和同包可用, destroy方法必须声明为public,此为系统调用

 

运行这个MyServlet1 类的实例,可以通过启动服务器,在浏览器输入如上web.xml文件中为其配置的url    

localhost:8080/servlet/MyServlet1             # 此虚拟路径没有设置到项目名而已

或者通过junit写单元测试代码,第一种方法运行结果如下

Connected to server
[2018-05-31 06:55:24,301] Artifact servletDemo1:war exploded: Artifact is being deployed, please wait...
[2018-05-31 06:55:24,808] Artifact servletDemo1:war exploded: Artifact is deployed successfully
[2018-05-31 06:55:24,809] Artifact servletDemo1:war exploded: Deploy took 507 milliseconds
调用了Servlet的构造函数
调用了init函数
调用service方法
调用了doPost方法
31-May-2018 18:55:33.938 信息 [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/home/lin/tomcat/webapps/manager]
31-May-2018 18:55:33.968 信息 [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/home/lin/tomcat/webapps/manager] has finished in [29] ms
/home/lin/tomcat/bin/catalina.sh stop
Using CATALINA_BASE:   /home/lin/.IntelliJIdea2018.1/system/tomcat/index_jsp_(2)_servletDemo1
Using CATALINA_HOME:   /home/lin/tomcat
Using CATALINA_TMPDIR: /home/lin/tomcat/temp
Using JRE_HOME:        /usr/jdk1.8
Using CLASSPATH:       /home/lin/tomcat/bin/bootstrap.jar:/home/lin/tomcat/bin/tomcat-juli.jar
31-May-2018 18:55:41.887 信息 [main] org.apache.catalina.core.StandardServer.await A valid shutdown command was received via the shutdown port. Stopping the Server instance.
31-May-2018 18:55:41.888 信息 [main] org.apache.coyote.AbstractProtocol.pause Pausing ProtocolHandler ["http-nio-8080"]
31-May-2018 18:55:41.891 信息 [main] org.apache.coyote.AbstractProtocol.pause Pausing ProtocolHandler ["ajp-nio-8009"]
31-May-2018 18:55:41.892 信息 [main] org.apache.catalina.core.StandardService.stopInternal Stopping service [Catalina]
调用了destroy方法
31-May-2018 18:55:41.916 信息 [main] org.apache.coyote.AbstractProtocol.stop Stopping ProtocolHandler ["http-nio-8080"]
31-May-2018 18:55:41.918 信息 [main] org.apache.coyote.AbstractProtocol.stop Stopping ProtocolHandler ["ajp-nio-8009"]
31-May-2018 18:55:41.936 信息 [main] org.apache.coyote.AbstractProtocol.destroy Destroying ProtocolHandler ["http-nio-8080"]
31-May-2018 18:55:41.937 信息 [main] org.apache.coyote.AbstractProtocol.destroy Destroying ProtocolHandler ["ajp-nio-8009"]
Disconnected from server