preface

Servlets are server-side Java applications that can produce dynamic Web pages. Through JSP execution can know the JSP is compiled into a. Class files, to view the file corresponding Java classes, found that the Java classes inherit from org. Apache. Jasper. Runtime. HttpJspBase class, HttpJspBase inherits from the HttpServlet class, so when a JSP is first run, it is essentially translated into a Servlet by the JSP engine, then compiled, and finally executed.

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

Servlet declaration cycle:

Load and instantiate

The Servlet container is responsible for loading and instantiating servlets. When the client sends the Servlet request to the server for the first time (in the web.xml file, the Servlet can be configured with the load-on-startup tag to create the Servlet instance immediately after the Web project is published), the Servlet container loads and creates the Servlet instance, (Note: Servlets are not loaded and instantiated by default when the Tomcat server or Web application on the server starts.) When the client (which can be a non-first-time client) sends the Servlet request to the server again, the server looks for the Servlet instance in memory and uses the found Servlet instance to process the user request.

During this process, the Servlet container creates a ServletConfig object that contains the initial configuration information for the Servlet. According to the URL address requested by the user, the Servlet container will find the Servlet class corresponding to the request based on the configuration information, and the container will create and manage the Servlet.

2. Initialize

After the Servlet container completes the instantiation of the Servlet class, the Servlet container calls the init() method of the Servlet (defined in the Javax.servlet.servlet interface) to initialize the Servlet. For each Servlet instance, the init () method is called only once. The purpose of initialization is to let the Servlet do the necessary preparatory work, such as establishing database connections, referencing other resources, and so on, before it can process the user request.

3. Handle requests

Once the Servlet is initialized, it is ready to receive user requests. When the Servlet container receives a client request for the Servlet, it first creates ServletRequest and ServletResponse objects for the request. The Servlet’s service () method is then called and these two parameters are passed to the service () method to process the client request. The Servlet instance gets the request from the client through the ServletRequest object and responds by calling the methods of the ServletResponse object. The request is processed, and the ServletRequest and ServletResponse objects are destroyed.

Regardless of whether the client sends the request in Get or POST, the request is handled by the Service method. The doGet and doPost methods are used to process the request, depending on how the client sends the request. The HttpServlet service method is used to process the request.

protected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        String method = req.getMethod();
        if (method.equals(METHOD_GET)) {
            long lastModified = getLastModified(req);
            if (lastModified == -1) {
                doGet(req, resp);
            } else {
                long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
                if (ifModifiedSince < lastModified) {
                    maybeSetLastModified(resp, lastModified);
                    doGet(req, resp);
                } else{ resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); }}}else if (method.equals(METHOD_HEAD)) {
            long lastModified = getLastModified(req);
            maybeSetLastModified(resp, lastModified);
            doHead(req, resp);
        } else if (method.equals(METHOD_POST)) {
            doPost(req, resp);
        } else if (method.equals(METHOD_PUT)) {
            doPut(req, resp);
        } else if (method.equals(METHOD_DELETE)) {
            doDelete(req, resp);
        } else if (method.equals(METHOD_OPTIONS)) {
            doOptions(req,resp);
        } else if (method.equals(METHOD_TRACE)) {
            doTrace(req,resp);
        } else {
            String errMsg = lStrings.getString("http.method_not_implemented"); Object[] errArgs = new Object[1]; errArgs[0] = method; errMsg = MessageFormat.format(errMsg, errArgs); resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg); }}Copy the code

4, destroy,

Destroying servlets is done by the Servlet container. By default, the first time a user sends a Servlet request, the Servlet loads, instantiates, initializes, and processes the user request, and when the request is processed, the Servlet typically stays in memory, waiting for the next request for the Servlet to be processed. When the next request for the Servlet arrives, the Servlet instance is fetched directly from memory and the request is processed. If Tomcat, the Web application server, is shut down (all Web applications on the server are shut down), or the Web application in which the Servlet resides is shut down, the Servlet instance is destroyed.

When a Web application is shut down, the Servlet container first calls the destroy method on the Servlet instance and then destroys the Servlet instance, as well as the ServletConfig object associated with the Servlet. Programmers usually release the resources that the Servlet consumes in the implementation of the destroy() method, such as closing database connections, closing file input/output streams, and so on.

The Servlet declaration cycle tells you that the Servlet object being created is a singleton.

Servlet2. X configuration

In the web.xml file, the URL accessed by the user is mapped to the specified servlet class by configuring the servlet element and servlet-mapping element under the node as follows:

<web-app> <! -- Omit other configurations --> <servlet> <! -- servlet-name specifies the servlet name, consistent with the servlet-name in the following servlet-mapping element --> <servlet-name>doLogin</servlet-name> <! - the servlet - class corresponds to the servlet class fully qualified name - > < the servlet class - > com. Jd. Serlvet. LoginServlet < / servlet class - > < / servlet > <servlet-mapping> <! -- servlet-name = servlet-name --> <servlet-name>doLogin</servlet-name> <! -- url-pattern sets the url of the current Servlet when it runs in the browser --> <url-pattern>/doLogin</url-pattern>
  </servlet-mapping>
</web-app>
Copy the code

The mapping between URL and Servlet is configured in the form of exact matching above. Next, two non-exact matching Servlet configuration methods are introduced:

<! -doAll requests under the Login path are sent bydo<servlet-mapping> <servlet-name>doLogin</servlet-name>
    <url-pattern>/doLogin/*</url-pattern> </servlet-mapping> <! -- All requests with the suffix.do are handled bydo<servlet-mapping> <servlet-name>doLogin</servlet-name> <! - not for/with / *. Do - > < url - the pattern > *. Do < / url - the pattern > < / servlet - mapping >Copy the code

After the mapping between URL and Servlet is configured, when the Servlet container receives a request, it first determines which Web application responds to the request, and then searches for the Servlet class corresponding to the URL in the Web. XML file of the Web application for processing.

Servlet initialization parameter Settings

When configuring servlets in the web.xml file, you can also pre-initialize the Servlet by adding init-param elements to the Servlet element, and get initialization parameters from the Servlet configuration file when the Servlet loads.

<! -- Omit other configuration --> <servlet> <servlet-name>doLogin</servlet-name> <servlet-class>com.jd.serlvet.LoginServlet</servlet-class> <! -- Configure multiple initialization parameters, > <init-param> <param-name>name</param-name> <param-value>Tom</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>doLogin</servlet-name>
    <url-pattern>/doLogin</url-pattern>
  </servlet-mapping>
Copy the code

How to get:

Call getInitParameter(String name);

@Override
public void init() throws ServletException {
	String name = getInitParameter("name");
	System.out.println(name);
}
Copy the code

GetInitParameter (String name) = getInitParameter(String name);

@Override
public void init(ServletConfig config) throws ServletException {
	String name = config.getInitParameter("name");
	System.out.println(name);
}
Copy the code

Servlet context (environment object) initialization parameter Settings

Sometimes initialization parameters need to be set not only for a single Servlet, but also for the environment object that contains all servlets in the Web reference, so that this parameter can be shared by all servlets, as follows:

<! -- omit other configuration --> <! -- Configure multiple initialization parameters, <context-param> <param-name>name</param-name> <param-value>Tom</param-value> </context-param> <servlet> <servlet-name>doLogin</servlet-name>
    <servlet-class>com.jd.serlvet.LoginServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>doLogin</servlet-name>
    <url-pattern>/doLogin</url-pattern>
  </servlet-mapping>
</web-app>
Copy the code

How to get:

A, call getServletContext () to get the Servlet context object, and then use this object to call getInitParameter.

@Override
public void init() throws ServletException {
	String name = getServletContext ().getInitParameter("name");
	System.out.println(name);
}
Copy the code

B. Call getServletContext () in ServletConfig to get the Servlet context object, and then use this object to call getInitParameter.

@Override
public void init(ServletConfig config) throws ServletException {
	ServletContext servletContext = config.getServletContext();
	String name = servletContext.getInitParameter("name");
	System.out.println(name);
}
Copy the code

The Servlet 3.0

Servlet API contains two packages javax. Servlet and javax.servlet. HTTP. Starting with Servlet3.0, in order to implement some new features of Servlet3.0, Javax. sevlet.annotation and Javax. sevlet.descriptor are added. The Tomcat server must be version 7.0 or later

One of the major innovations of Servlet3.0 is support for annotations. By using annotations to define and deploy servlets, programmers do not need to configure servlets in a web.xml file, as follows:

@WebServlet(name="doLogin",urlPatterns="/doLogin",initParams={@WebInitParam(name="name",value="Tom")})
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.sendRedirect("success.jsp"); }}Copy the code

Description:

Name attribute: Specifies the Servlet name, similar to the servlet-name element in web.xml;

The urlPatterns attribute: specifies access urls, similar to the URL-pattern element in web.xml; Can be arrays, urls separated by commas.

InitParams property: sets the initialization parameter. This property uses the @webinitParam annotation to set a single initialization parameter. In the @webinitParam annotation, the name attribute specifies the parameter name, similar to the param-name element in web.xml; The value attribute specifies the parameter value, similar to the param-value element in web.xml. You can configure multiple @webInitParam annotations in the initParams property to initialize multiple parameters.

wb.xml:

<! 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>lucy</param-value> </context-param> <servlet> <servlet-name>TestServlet</servlet-name> <display-name>TestServlet</display-name> <description></description> <servlet-class>com.jd.servlet.TestServlet</servlet-class> <init-param> <param-name>mobile</param-name> <param-value>120</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>Copy the code

TestServlet.java:

package com.jd.servlet; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class TestServlet */ public class TestServlet extends HttpServlet { private static final long serialVersionUID = 1L; //Servlet objects belong to singleton (only one object exists in the cache until the program ends) publicTestServlet() {// Is used to assign values to member variables, triggering object creation: by default, object creation is executed the first time the Servlet is used; <load-on-startup>1</load-on-startup> </load-on-startup> </load-on-startup> </load-on-startup> System.out.println("TestServlet"+this);
       
    }
 
	//
	@Override
	public void destroy() {
		super.destroy();
		 System.out.println("destroy"+this); Override public void init() throws ServletException {// Initialize; For each Servlet instance, the creation object executes the init() method and is called super.init() only once; String name=getServletContext().getInitParameter("name"); // Call the public argument system.out.println ("1111111"+name);
		System.out.println("init())"+this);
	}
	
 
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		String name=config.getServletContext().getInitParameter("name"); // Call the public argument system.out.println ("Hello"+name);
		String mobile=config.getInitParameter("mobile"); // Call the private argument system.out.println ("Fight"+mobile);
		System.out.println("init(config))"+this); } // The request reaches the service first to determine which method to execute,doGet ordoPost
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.service(req, resp);
		System.out.println("service"+this); } //a tag, the form method is the asynchronous default for get methodstypeIt's get protected voiddoGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 System.out.println("doGet"+this); } // The form method is the post method specified asynchronouslytypePost protected voiddoPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 System.out.println("doPost"+this); }}Copy the code

The last

Thank you for reading here, after reading what do not understand, you can ask me in the comments section, if you think the article is helpful to you, remember to give me a thumbs up, every day we will share Java related technical articles or industry information, welcome to pay attention to and forward the article!