Detailed Servlet life cycle

table of Contents

One, the concept of Servlet

Second, the life cycle

Three, doGet () method and doPost () method


One, the concept of Servlet

Servlet is a server-side Java application that can produce dynamic Web pages . Through the JSP execution process, you can know that JSP is finally compiled into a .class file . Check the Java class corresponding to the file. It is found that the Java class inherits from the org.apache.jasper.runtime.HttpJspBase class, and HttpJspBase inherits from the HttpServlet class. It can be seen that the JSP is essentially translated into a Servlet by the JSP engine when it runs for the first time, then compiled, and finally executed.

The custom Servlet class inherits the HttpServlet abstract class, the HttpServlet abstract class inherits from the GenericServlet abstract class, and the GenericServlet abstract class implements the Servlet, ServletConfig and Serializable interfaces.

Second, the life cycle

web.xml code display:

 <!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>
  <context-param>
  		<param-name>name</param-name>
  		<param-value>Tom</param-value>
  </context-param>
  <servlet>
  	<servlet-name>TestServlet</servlet-name>
  	<servlet-class>com.jd.servlet.TestServlet</servlet-class>
  	<init-param>
  		<param-name>mobile</param-name>
  		<param-value>110</param-value>
  </init-param>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  	<servlet-name>TestServlet</servlet-name>
  	<url-pattern>/TestServlet</url-pattern>
  </servlet-mapping>
</web-app>

1. Loading and instantiating the
Servlet container is responsible for loading and instantiating the Servlet. When the client sends the Servlet request to the server for the first time, the Servlet container will load and create a Servlet instance (Note: By default, the Servlet is not loaded and instantiated when the Tomcat server or the Web application on the server starts). When the client (which may be a client other than the first requesting client) sends the Servlet request to the server again, the server will look for the Servlet instance from memory and use the found Servlet instance to process the user request.

In this process, the Servlet container will create a ServletConfig object, which contains the initial configuration information of the Servlet. According to the URL address requested by the user, the Servlet container will look up the Servlet class corresponding to the request according to the configuration information, and the Servlet will be created and managed by the container.

Code display:

//Servlet对象属于单实例(程序运行结束之前,缓存中只有一个对象)
    public TestServlet() {//用于成员变量赋值,会触发对象创建:默认情况下,第一次使用该Servlet时创建该对象;如果<loan-on-startup>1</loan-on-startup>,则Servlet对象随着Tomcat的启动而启动
        super();
        System.out.println("TestServlet"+this);
    }

The Sevlet object is a single instance (before the program runs, only one object exists in the cache

The Sevlet object is a single instance (only one object exists in the cache before the program runs) By default, the object is created when the servlet is used for the first time; if you add configuration in web.xml: <load-on-startup>1</ load-on-startup>, the servlet object is automatically created by default when Tomcat is started .
Code running results:

2. Initialization
After the Servlet container completes the instantiation operation of the Servlet class, the Servlet container will call the init() method of the Servlet (defined in the javax.servelt.Servlet interface) to initialize the Servlet. For each Servlet instance, the init() method will only be called once. The purpose of initialization is to allow Servlet to do some necessary preparations before processing user requests, such as establishing a database connection and referencing other resources.

Code display:

@Override
public void init() throws ServletException {//Servlet对象后执行,由于Servlet对象属于单实例,仅仅创建一次,因此只执行一次,用于获取初始化web.xml中数据,该方法立即执行,由于Servlet对象属于单实例,仅仅创建一次,因此只执行一次
	super.init();
	String name = getServletContext().getInitParameter("name");
	System.out.println("##########"+name);//获取多个Servlet共享的值
		
	super.getInitParameter("mobile");
	String mobile = super.getInitParameter("mobile");//获取自己Servlet的值
	System.out.println("%%%%%%%%%%%"+mobile);
}
    
    
    
@Override
public void init(ServletConfig config) throws ServletException {Servlet对象后执行,用于获取初始化web.xml中数据,由于Servlet对象属于单实例,仅仅创建一次,因此只执行一次
	super.init(config);
	System.out.println("init(ServletConfig config)"+this);
	String name =  config.getServletContext().getInitParameter("name");
	System.out.println("@@@@@@@@@@@@@@"+name);//获取多个Servlet共享的值
		
	String mobile = config.getInitParameter("mobile");//获取自己Servlet的值
	System.out.println("~~~~~~~~~~~~~~"+mobile);
}

Note: Distinguish between two different initialization methods: the difference between participation and call without parameters

After the Servlet object is created, this method is executed immediately to obtain the initialization data in the web.xml file . Since the Servlet object is a singleton, it will only be created once when creating the object, so this method will only be executed once.

3. After the processing request
servlet is initialized, it is in a ready state waiting to receive user requests. When the Servlet container receives the client's request for the Servlet, it will first create ServletRequest and ServletResponse objects for this request, and then call the service() method of the Servlet and pass these two parameters to the service() method to process the client request. The Servlet instance obtains the client's request through the ServletRequest object, and responds by calling the method of the ServletResponse object. After the request is processed, the ServletRequest and ServletResponse objects are destroyed.

Regardless of whether the client sends the request by Get or POST, the request is handled by the service method. During the processing of the service method, the doGet and doPost methods are called for processing separately according to the different ways the client sends the request. The service method in the HttpServlet class can be used to understand the calling process.

Code display:

//任何请求优先到达service——进而通过该方法确定执行doGet还是doPost
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
	super.service(arg0, arg1);//调用父类
	System.out.println("service"+this);
}

Any request arrives at the service first-and then use this method to determine whether to execute doGet or doPost

4. Destruction
Destroying the Servlet is completed by the Servlet container. By default, the user sends a Servlet request for the first time. The Servlet loads, instantiates, initializes, and processes user requests. When the request is processed, the Servlet usually resides in memory and waits for the next servlet to be processed. request. When the next request for the Servlet arrives, the Servlet instance is directly obtained from the memory and the request is processed. If the web application server Tomcat is closed (all web applications on the server are closed), or the web application where the servlet is located is closed, the servlet instance will be destroyed.

When the Web application is closed, the Servlet container will first call the destroy method of the Servlet instance, then destroy the Servlet instance, and also destroy the ServletConfig object associated with the Servlet. The programmer usually releases the resources occupied by the servlet in the implementation of the destroy() method, such as closing the database connection, closing the file input/output stream and so on.

Through the Servlet life cycle, you can know that the created Servlet object is a singleton.

Code display:

//Servlet对象销毁之前调用(只能销毁一次),用于释放资源,由于Servlet对象属于单实例,仅仅创建一次,所以只执行一次,Tomcat服务器关闭时调用,项目重新发布前 
@Override
public void destroy() { 
	super.destroy();
	System.out.println("destroy"+this);
}

Summary: After the code is changed, the destroy method will be executed, and the conditions for calling the destroy method:
1. The destroy method is called when Tomcat is closed;
2. The destroy method is called before the project is republished after the code is changed.
Mainly used to release resources in web.xml.

Three, doGet () method and doPost () method

doGet() method:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	System.out.println("doGet"+this);
}

Conditions of use:
1. A tag link;
2. The default attribute value of the method tag attribute in the form or specified as get; 3. The default value of type in asynchronous or specified as get.

doPost() method :

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	System.out.println("doPost"+this);
}

Conditions of use:
1. The form specifies the method tag attribute post;
2. In the asynchronous mode, the type is specified as post.

Guess you like

Origin blog.csdn.net/m0_46383618/article/details/107597195