The life cycle of the servlet's introductory learning

Source: Internet
Author: User

I. What is a servlet

A servlet is a server-side applet written in the Java language that resides in the Web server and runs in it, extending the dynamic processing capabilities of the Web server.

    1. Java classes written in the Java language
    2. Running in the Web container
    3. Used to process client requests

Static Web technology----> Traditional CGI technology----->servlet Technology

  

Two. Servlet life cycle and how it works

Principle of execution:

    1. The client sends an HTTP request to the Web server
    2. The WEB server forwards the request to the servlet
    3. The Servlet processes the request
    4. The Servlet sends the response to the Web server
    5. The WEB server forwards the response to the client

  

Life cycle:

The life cycle of the servlet is controlled by the Web container, and the operation of the Web container when the servlet is requested:

    1. Load and Instantiate: If the servlet instance does not exist, the Web container loads the Servlet class first and then creates an instance of the servlet
    2. Initialize: Then call its init () method to initialize.
    3. Request Processing: Invokes the service () method and passes the request and response objects to it.
    4. Service termination: When the Web container detects that a servlet instance should be removed, it calls its destroy () method so that the instance can free the resources it uses.

  

  

      1. The Web Client makes an HTTP request to the servlet container (Tomcat)
      2. The servlet container receives a request from the Web client
      3. The servlet container creates a HttpRequest object that encapsulates the information requested by the Web client into this object.
      4. Servlet container creates a HttpResponse object
      5. The servlet container invokes the service method of the HttpServlet object, passing the HttpRequest object and the HttpResponse object as arguments to the HttpServlet object.
      6. HttpServlet invokes the method of the HttpRequest object to obtain the HTTP request information.
      7. HttpServlet calls the methods of the HttpResponse object to generate the response data.
      8. The servlet container passes the results of the HttpServlet response to the Web Client.

Working principle:

How Servlets work:

1, first of all, a simple explanation of the servlet receiving and responding to the customer request process, first the customer sends a request, the servlet is called the Service () method to respond to the request, through the source code is visible, theservice () method to match the way of the request, Choose to call Doget,dopost and other methods , and then enter the corresponding method to invoke the logical layer method, to achieve the response to the customer. There are no doget (), DoPost (), and so on in the Servlet interface and Genericservlet, these methods are defined in HttpServlet, but all return error information, so Each time we define a servlet, we must implement these methods such as Doget or Dopost.

2, each custom servlet must implement the Servlet interface, the Servlet interface defines five methods, of which the more important three methods involve the life cycle of the servlet, respectively, the above mentioned Init (), service (), Destroy ( Method Genericservlet is a generic, non-protocol-specific servlet that implements the Servlet interface. And HttpServlet inherits from Genericservlet, so HttpServlet also implements the Servlet interface. So we only need to inherit httpservlet when we define the servlet.

3. The servlet interface and Genericservlet are not specific to any protocol, and HttpServlet is a class specific to the HTTP protocol, so the service () method is implemented in HttpServlet. And the request ServletRequest, Servletresponse Strong to HttpRequest and HttpResponse.

 Public voidService (ServletRequest req,servletresponse res)throwsservletexception,ioexception{HttpRequest request;      HttpResponse response; Try{req=(HttpRequest) request; Res=(HttpResponse) response; }Catch(classcastexception e) {Throw NewServletexception ("Non-http Request Response"); } service (Request,response);}

The code finally calls HttpServlet's own service (Request,response) method, and then calls the corresponding Doxxx method as requested, because the Doxxx method in HttpServlet returns an error message. So we need to override these methods in our custom servlet!

protected void doget (HttpServletRequest res,httpservletresponse resp)
throws Servletexception,ioexception
{
String protocol = Req.getprotocol ();
String msg = istrings.getstring ("http.method_get_not_supported");
if (protocol.equals ("1.1"))
   {
Resp.senderror (httpservletresponse.sc.method.not.allowed,msg);
    }
Esle
    {
Resp.senderror (httpservletresponse.sc_bad_request,msg);
    }
}

 

Three. Detailed Life cycle

  

Load:

The servlet container loads the servlet at the following times:

1. When the servlet container starts, it automatically loads some servlets, and implements it only on the web. Add the following code between <Servlet></Servlet> in the XML file:

<servlet>        <Servlet-name>Init</Servlet-name>        <Servlet-class>Org.xl.servlet.InitServlet</Servlet-class>        <Load-on-startup>1</Load-on-startup></servlet>

(where the Ps:servlet class resides: It can be a local file system, a remote file system, other network resources)

(The Ps:servlet container is responsible for loading and instantiating, whether the servlet is loaded automatically when the container starts, as determined by the <load-on-startup> property set in Web. xml)

    

2. After the servlet container is started, the customer sends the request to the servlet for the first time

The client makes a request to the servlet for the first time, and the servlet container determines whether the specified Servlet object exists in memory, and if not, creates it

(then create a HttpRequest, HttpResponse object based on the client's request to invoke the service method of the Servlet object)

3. After the servlet class file is updated, remount the servlet

  Initialization

After the servlet is loaded, the servlet container creates a servlet instance and invokes the servlet's init () method for initialization. The init () method is called only once throughout the servlet's life cycle.

    Call the Init () method to complete the initialization work before processing the user request (for example, establishing a database connection, obtaining configuration information [via ServletConfig object]).

    If initialization fails, the Servletexception or Unavailableexception exception is thrown and the instance is destroyed.

Genericservlet provides two forms of the Init () method:

Public void Init () throws servletexception;

The init () method is used to allow you to extend the Genericservlet class, and when you use this method, you do not need to store the Config object or call Super.init (config).

Public void init (servletconfig config) throws servletexception;

The init (servletconfig config) method is an easy way to initialize the life cycle of this servlet.

The init (servletconfig config) method stores the Config object and then calls Init (). If you overload this method, you must call Super.init (config) so that other methods of the Genericservlet class will work correctly.

  Request Processing:

    When the servlet instantiates, it receives the client request, responds, and is implemented by invoking the service () method.

(The servlet container creates ServletRequest objects and Servletresponse objects that are specific to this request, and then invokes the Servlet's service method.) )

Because the servlet uses a multithreaded mechanism to provide services, the method is called simultaneously and multiple times. Each request calls its own service () method, but be aware of thread safety .

When a user implements a specific servlet, the service () method is generally not overloaded, and theWeb container calls the service () automatically doget (), DoPost (), DoPut (), DoDelete (), depending on how the request is called. One or more of the following, so as long as the corresponding doxxx () is overloaded.

  Termination of Service:

The server frees the resource used by the Servlet runtime by calling the Destroy method without throwing an exception.

    

Note: Do not use the servlet's destruction mechanism as the only mechanism for saving states such as access counts or cookie lists to disk. Because the Web container may crash, the Destroy () method is not always executed.

Four. Servlet versus JSP comparison:

There are many similarities where dynamic Web pages can be generated.

JSP advantage is good at web page production, generate dynamic pages more intuitive, the disadvantage is not easy to track and error.

The servlet is a pure Java language and specializes in processing processes and business logic, with the drawback that generating dynamic Web pages is not intuitive.

The life cycle of the servlet's introductory learning

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.