Servlet-related interfaces and Servlet Lifecycle

Source: Internet
Author: User

The most direct way to create a servlet class is to implement javax. servlet. servlet interface: The servlet interface is defined as follows. Five methods are defined. The servlet lifecycle is embodied in these methods:

 1 public interface Servlet { 2     public void init(ServletConfig config) throws ServletException; 3      4     public ServletConfig getServletConfig(); 5      6     public void service(ServletRequest req, ServletResponse res) 7             throws ServletException, IOException; 8              9     public String getServletInfo();10     11     public void destroy();12 }

1. Load and instantiate

First, define a demoservlet to implement the servlet interface, override the methods in the interface, print the respective method names, and print a sentence in the non-parameter constructor:

 1 public class DemoServlet implements Servlet { 2  3     public DemoServlet() { 4         System.out.println("constructor…"); 5     } 6  7     @Override 8     public void destroy() { 9         System.out.println("DemoServlet.destroy()");10     }11 12     @Override13     public ServletConfig getServletConfig() {14         System.out.println("DemoServlet.getServletConfig()");15         return null;16     }17 18     @Override19     public String getServletInfo() {20         System.out.println("DemoServlet.getServletInfo()");21         return null;22     }23 24     @Override25     public void init(ServletConfig config) throws ServletException {26         System.out.println("DemoServlet.init()");27     }28 29     @Override30     public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {31         System.out.println("DemoServlet.service()");32     }33 34 }

To be managed by containers, You need to configure servlet in Web. xml:

1 <servlet>                                           2     <servlet-name>demo</servlet-name>               3     <servlet-class>servlet.DemoServlet</servlet-classs>4 </servlet>                                          5 <servlet-mapping>                                   6     <servlet-name>demo</servlet-name>               7     <url-pattern>/demo</url-pattern>                8 </servlet-mapping>                                  

Start the server and request the servlet through "http: // localhost: 8080/$ {contextpath}/demo". The console prints the following output:

Refresh the page and request the servlet again. The console prints the following information. The second request only executes the Service (servletrequest req, servletresponse res) method:

When the server receives the request. if no matching servlet is found in the configuration in XML, Error 404 is returned. If no matching servlet class is found, check whether the servlet class instance already exists in the server based on the fully qualified name of the configured servlet class, if yes, use it directly to process the request (the servlet instance already exists in the second request above, and directly call the service (servletrequest req, servletresponse res) method of the instance .); If this parameter does not exist, an instance is created by reflection based on the fully qualified name (the common construction method without parameters is called ). It can be seen from this that if no accessible non-parameter constructor is provided, an error is returned:

1 // provides a construction method with parameters, covering the Default Construction Method without parameters 2 Public demoservlet (string s) {3 system. Out. println ("constructor... "); 4}

 

The server uses reflection to call the class. newinstance () method to create an instance. If no parameter constructor can be accessed, an error is reported.

2. Initialization

We can see from the above that the init (servletconfig config) method was called to complete initialization during the first request to create a servlet instance. Initialization is only performed when an instance is created. Subsequent requests are not initialized and the Service () method is called directly to process requests. When the server initializes the servlet, it will first prepare a servletconfig object, through which the initialization parameter information can be obtained from the application configuration information; database Connection establishment and other tasks are usually completed in the initialization phase.

The servletconfig interface defines four methods for obtaining initialization parameter information:

1 public interface servletconfig {2 // obtain the servlet name, that is, in the web. information about the <servlet-Name> demo </servlet-Name> node configuration in XML 3 Public String getservletname (); 4 5 // get the servlet context object 6 Public servletcontext getservletcontext (); 7 8 // get the initialization parameter value 9 Public String getinitparameter (string name) based on the parameter name; 10 11 // get all the initialization parameter names 12 public enumeration <string> getinitparameternames (); 13}

You can configure initialization parameters in Web. xml:

 1 <servlet>                                             2     <servlet-name>demo</servlet-name>                 3     <servlet-class>servlet.DemoServlet</servlet-class> 4     <init-param>                                      5         <param-name>username</param-name>             6         <param-value>admin</param-value>              7     </init-param>                                     8 </servlet>                                            9 <servlet-mapping>                                    10     <servlet-name>demo</servlet-name>                11     <url-pattern>/demo</url-pattern>                 12 </servlet-mapping>                                   

Note:If. <load-on-startup> 1 </load-on-startup> is configured in XML. The servlet completes instance creation and initialization when the server is started, instead of the first request:

1 <servlet>                                                 2     <servlet-name>demo</servlet-name>                     3     <servlet-class>servlet.DemoServlet</servlet-class>    4     <load-on-startup>1</load-on-startup>                  5 </servlet>                                                6 <servlet-mapping>                                         7     <servlet-name>demo</servlet-name>                     8     <url-pattern>/demo</url-pattern>                      9 </servlet-mapping>                                        

3. Process requests

The server calls the Service (servletrequest req, servletresponse res) method to process the request. Before processing the request, the init () method must be successfully executed. Before the server calls the Service (servletrequest req, servletresponse res) method, it has prepared the servletrequest object and the servletresponse object, and passed it as a parameter to the Service (servletrequest req, servletresponse res) method.

The servletrequest interface and the servletresponse interface define methods for processing requests and responses:

4. Destroy

When the container detects that a servlet instance should be removed from the service, the container will call the destroy () method of the Instance so that the instance can release its resources, save the data to the persistent storage device. When the memory needs to be released or the container is closed, the container will call the destroy () method of the servlet instance. After the destroy () method is called, the container releases the servlet instance and the instance is recycled by the Java garbage collector. If you need this servlet to process the request again, the servlet container will create a new servlet instance.

The destroy () method is the same as the init () method. It is executed only once in the servlet lifecycle, but the destroy () method is not always executed. For example, when the server is terminated abnormally, the destroy () method cannot be executed.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.