Introduction to servlet principle

The servlet life cycle is divided into three phases:

  1. Initialization phase: call init() method

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

  3, call destroy() method in termination phase

Servlet initialization phase:

  Servlet container loads servlets at the following times:

    1. When the servlet container starts, some servlets are automatically loaded. To realize it, you only need to add the following code between <Servlet></Servlet> in the web.XML file:
<loadon-startup>1</loadon-startup>

    2, After the servlet container is started, the client sends a request

    3 to the servlet for the first time. After the servlet class file is updated, the

  servlet is reloaded. After the servlet is loaded, the servlet container creates a servlet instance and calls the init() method of the servlet for initialization. The init() method is called only once during the entire life cycle of the servlet.

    

Servlet works:

  First, briefly explain the process of servlet receiving and responding to client requests. First, the client sends a request, and the servlet calls the service() method to respond to the request. As can be seen from the source code, the service() method matches the request method. Choose to call doGet, doPost and other methods, and then enter the corresponding method to call the method of the logic layer to realize the response to the customer. There are no doGet, doPost, etc. methods in the Servlet interface and GenericServlet. These methods are defined in HttpServlet, but they all return error information. Therefore, every time we define a servlet, we must implement doGet or doPost, etc. method.

  Each custom servlet must implement the servlet interface. There are five methods defined in the servlet interface. The three most important methods involve the life cycle of the servlet, namely init() and service() mentioned above. , destroy () method. GenericServlet is a generic, not specific to any protocol Servlet, it implements the Servlet interface. HttpServlet inherits from GenericServlet, so HttpServlet also implements the Servlet interface. So we only need to inherit HttpServlet when we define 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 ServletRequest and ServletResponse are forced into HttpRequest and HttpResponse.
public void service(ServletRequest req, ServletResponse res)
  throws ServletException,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);
}

    At the end of the code, HTTPServlet's own service(request,response) method is called, and then the corresponding doXXX method is called according to the request, because the doXXX methods in HttpServlet all return error information,
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 code, there are no secrets!

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

Servlet response request stage:

=============== ===================================================== ====


The servletresponse and servletrequest created by servlet contain client information, url, etc., especially the instance initialized by url access, all contain client information. Of course, if there is no servlet-map, you can pass <loadon-startup>1</loadon- startup>Initialization, there is no url information at this time, but there is still client information. The service method is the source of client information parameters. Here, the servletrequest will be converted into httpservletquest, enter the servlet class corresponding to the url according to the parameters in the url, and select the jump method to realize the action function


============================================= =============================
  For a user's request to a servlet, the servlet container will create a ServletRequest object and a ServletResponse object specific to the request. Then call the service method of the servlet. The service method obtains the client request information from the ServletRequest object, processes the request, and returns the response information to the client through the ServletResponse object.

  For Tomcat, it will put the passed parameters in a Hashtable, the definition of the Hashtable is:

private Hashtable<String String[]> paramHashStringArray = new Hashtable<String String[]>();

  This is a String- ->String[] key-value map.

  HashMap is thread-unsafe, Hashtable is thread-safe.

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

Servlet termination phase:

  when the WEB application is terminated, or the servlet container terminates, or the servlet container When reloading a new instance of servlet, the servlet container will first call the destroy() method of the servlet, in which the resources occupied by the servlet can be released.

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

When the servlet is created:

  1. By default, when the WEB client first requests When accessing a servlet, the WEB container will create an instance of the servlet.

  2. When the <load-on-startup> sub-element is specified in the <servlet> element in the web.xml file, the servlet container will create and initialize the servlet objects in sequence when starting the web server.

  Note: In the web.xml file, some servlets have only <serlvet> elements and no <servlet-mapping> elements, so we cannot access these servlets by url. This kind of servlet usually configures a <servlet> element. The <load-on-startup> sub-element allows the container to automatically load these servlets at startup and call the init() method to complete some global initialization work.


When the web application is started:

  1. When the servlet container starts, all web applications will be started

  2. The controller starts the web application

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

Servlet and JSP comparison:

  There are many similarities, can generate dynamic web pages.

  The advantage of JSP is that it is good at making web pages, and it is more intuitive to generate dynamic pages. The disadvantage is that it is not easy to track and debug.

  Servlet is pure Java language, which is good at processing flow and business logic. The disadvantage is that it is not intuitive to generate dynamic web pages.


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327069857&siteId=291194637