The life cycle and how the servlet works

Source: Internet
Author: User

The servlet life cycle is divided into three phases:

1, Initialize phase call init () method

2, call the service () method in response to the customer request phase

3, Terminate phase call Destroy () method

Servlet initialization phase:

The servlet container loads the servlet at the following times:

The 1,servlet container starts automatically when certain servlets are loaded to implement it only on the web. Add the following code between <Servlet></Servlet> in the XML file:?

<loadon-startup> 1 </loadon-startup>

2, after the servlet container is started, the customer first sends a request to the servlet

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

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.

    

How Servlets work:

A simple explanation of the servlet's process of receiving and responding to a customer request begins with the client sending a request that the servlet responds to the request by invoking the service () method, which is visible through the source code, matches the request in the service () method, and chooses to call Doget , Dopost and so on, and then into the corresponding method to invoke the logical layer of the method to achieve 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 of them return error information, so each time we define a servlet, Must implement these methods such as Doget or Dopost.

Each custom servlet must implement the Servlet interface, which defines five methods in the Servlet interface, of which the more important three methods relate to the servlet's life cycle, which is 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.

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 is ServletRequest, Servletresponse Strong to HttpRequest and HttpResponse.?

public void Service (ServletRequest req,servletresponse Res)      throws Se rvletexception,ioexception {       HttpRequest request;         HttpResponse response;          try       {           req = (httprequest) request;           res = (httpresponse) response;        catch (classcastexception e)        {           throw new Servletexception ("Non-http Request Response");        }        Service (request,response); }

The code finally calls HttpServlet's own service (Request,response) method, then calls the corresponding Doxxx method, because the Doxxx method in HttpServlet returns an error message.

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); } }

So we need to override these methods in our custom servlet.

    in front of the source, there is no secret.

--------------------------------------------------------------------------------------------------------------- ------------------

The servlet responds to the request phase:

For a user to reach the servlet request, the servlet container creates the ServletRequest object and the Servletresponse object that are specific to the request, and then invokes the Servlet's service method. The service method obtains the customer request information from the ServletRequest object, processes the request, and returns the response information to the customer through the Servletresponse object.

For Tomcat, it will put the passed parameters in a Hashtable, the Hashtable is defined as:

?

Private hashtable<string string[]> Paramhashstringarray = new hashtable<string string[]> ();

This is a string-->string[] key-value mapping.

HashMap thread is unsafe, hashtable thread is safe.

--------------------------------------------------------------------------------------------------------------- --------------------

servlet termination phase:

When the Web application is terminated, or the servlet container terminates, or the servlet container reloads a new instance of the servlet, the servlet container calls the servlet's Destroy () method first, in the Destroy () method, you can release the resources that the servlet occupies.

--------------------------------------------------------------------------------------------------------------- --------------------

When the servlet was created:

1, by default, when a Web client first requests access to a servlet, the Web container creates an instance of the servlet.

2, when the <load-on-startup> child element is specified in the <servlet> element in the Web. xml file, the Servlet container will create and initialize the Servlet object in the order that it starts the server.

Note: In the Web. xml file, some servlets have only <serlvet> elements, there are no <servlet-mapping> elements, so we cannot access these servlets in a URL way. This servlet typically configures a <load-on-startup> child element in the <servlet> element, allowing the container to automatically load these servlets at startup and invoke the Init () method to accomplish some global initialization.


When the Web app is started:

1, when the servlet container is started, all Web applications will be launched

2, the controller launches the Web App

--------------------------------------------------------------------------------------------------------------- --------------------------------

Servlet vs. 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.

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.