servlet learning notes: the architecture of servlet

Keywords: xml Tomcat JSP Java

Articles Catalogue

1. Overall structure

2. Common methods

2.1 Servlet Common Methods

  • void init(ServletConfig config): initialization
  • void service(ServletRequest request, ServletResponse response): Service processing business logic
  • void destroy(): destruction
  • ServletConfig getServletConfig(): Gets the configuration object of the current servlet

2.2 Generic Servlet common methods

  • Except for the service method, which has not been implemented in detail, the others have been implemented.
  • If we want to initialize the servlet ourselves, we can override the init() method.
  • View the source code for the init() method
    • 1. Enter HttpServlet

    • 2. Enter Generic Servlet
    • 3. Find the init method

Common methods of 2.3Http Servlet

  • The service is implemented, the parameters are coercively converted, and the overloaded service method is invoked.

  • The overloaded service method gets the request and calls the corresponding doGet()/doPost() method according to the different requests.

  • View source code

  • public void service(ServletRequest req, ServletResponse res)

      public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
            HttpServletRequest request;
            HttpServletResponse response;
            try {
            	//Strong turn
                request = (HttpServletRequest)req;
                response = (HttpServletResponse)res;
            } catch (ClassCastException var6) {
                throw new ServletException("non-HTTP request or response");
            }
    		//Call this overloaded method
            this.service(request, response);
        }
    

- Note the parameter type

  • Enter overloaded service
  • protected void service(HttpServletRequest req, HttpServletResponse resp)
  • Note the parameter type
  • The method GET/POST to get the request first
  • Then make a judgment according to the method.
  protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getMethod();
        long lastModified;
        if (method.equals("GET")) {
            lastModified = this.getLastModified(req);
            if (lastModified == -1L) {
                this.doGet(req, resp);
            } else {
                long ifModifiedSince;
                try {
                    ifModifiedSince = req.getDateHeader("If-Modified-Since");
                } catch (IllegalArgumentException var9) {
                    ifModifiedSince = -1L;
                }

                if (ifModifiedSince < lastModified / 1000L * 1000L) {
                    this.maybeSetLastModified(resp, lastModified);
                    this.doGet(req, resp);
                } else {
                    resp.setStatus(304);
                }
            }
        } else if (method.equals("HEAD")) {
            lastModified = this.getLastModified(req);
            this.maybeSetLastModified(resp, lastModified);
            this.doHead(req, resp);
        } else if (method.equals("POST")) {
            this.doPost(req, resp);
        } else if (method.equals("PUT")) {
            this.doPut(req, resp);
        } else if (method.equals("DELETE")) {
            this.doDelete(req, resp);
        } else if (method.equals("OPTIONS")) {
            this.doOptions(req, resp);
        } else if (method.equals("TRACE")) {
            this.doTrace(req, resp);
        } else {
            String errMsg = lStrings.getString("http.method_not_implemented");
            Object[] errArgs = new Object[]{method};
            errMsg = MessageFormat.format(errMsg, errArgs);
            resp.sendError(501, errMsg);
        }

    }

3.Servlet life cycle (important)

Define a LifeServlet class, inherit the Servlet interface, implement init(),service(),destroy() methods, to illustrate the life cycle of the servlet

3.1 Define a LifeServlet class

	package com.zqx.c_life;

import javax.servlet.*;
import java.io.IOException;

/**
 * 20190810
 * Implementing Servlet Interface
 * Explain the life cycle of Servlet
 */
public class LifeServlet implements Servlet {


    /**
     * Initialization method
     * Executor: Server
     * Number of executions: once
     * Execution timing: Default first access time
     */
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("5555555555555555");
    }
    /**
     * service
     * Executor: Server
     * Number of executions: Request execution once
     * Timing of execution: when the request comes
     */
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("666666666666666");
    }
    /**
     * Destruction
     * Executor: Server
     * Number of executions: only once
     * Execution timing: When the servlet is removed or when the server shuts down normally
     */
    @Override
    public void destroy() {
        System.out.println("4444444444444444");

    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }



    @Override
    public String getServletInfo() {
        return null;
    }


}

3.2 HTML page

 <a href="/servlet/life?name=tom">life cycle</a>

3.3web.xml

 <servlet>
        <servlet-name>LifeServlet</servlet-name>
        <servlet-class>com.zqx.c_life.LifeServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LifeServlet</servlet-name>
        <url-pattern>/life</url-pattern>
    </servlet-mapping>

3.4 Observations

3.5 Summary

void init(ServletConfig config): initialization

  • Initialization method
  • Executor: Server
  • Number of executions: once
  • Execution timing: When the first visit is made by default (indicating that it can be set by itself)

void service(ServletRequest request,ServletResponse response): Service processing business logic

  • service
  • Executor: Server
  • Number of executions: Request execution once
  • Timing of execution: when the request comes

void destroy(): destruction

  • Destruction
  • Executor: Server
  • Number of executions: only once
  • Execution timing: When the servlet is removed or when the server shuts down normally

A servlet is a single-threaded multi-instance. By default, the server creates a servlet and invokes init method to initialize it, and invokes service method once. Whenever there is a new request, the server creates a thread and invokes service method to execute its own business logic. When the serlvet is removed, the server serves. When the server shuts down normally, the server calls the servlet's destroy method to implement the destruction operation.

4.url-pattern configuration

After creating a servlet, the servlet must be configured in web.xml to be accessed, with a < url-pattern > tag that determines the path to a servlet.

4.1 A servlet can be mapped by multiple paths

 <servlet>
        <servlet-name>LifeServlet</servlet-name>
        <servlet-class>com.zqx.c_life.LifeServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LifeServlet</servlet-name>
        <url-pattern>/life</url-pattern>
    </servlet-mapping>
    <!--One servlet Can be mapped by different paths-->
    <servlet-mapping>
        <servlet-name>LifeServlet</servlet-name>
        <url-pattern>/life01</url-pattern>
    </servlet-mapping>
  • The above example shows that com.zqx.c_life.LifeServlet can be accessed by paths/life and/life01.

Three Writings of 4.2

  • Perfect matching: Must start with "/", for example: / hello /a/b/c
  • Catalog Matching: Must start with "/" and end with "*", for example: / a/*/*
  • Suffix name matching begins with "*" and ends with characters such as *. jsp *.do *.action.
  • Priority: Full Match > Directory Match > Suffix Name Match

4.3 Test

Assume:

  • Servlet1 maps to / abc/*
  • Servlet2 maps to/*
  • Servlet 3 maps to / abc
  • Servlet4 maps to *.do
    Q:
  • When the request URL is "/abc/a.html", "abc/" and "/", which servlet responds
    • Perfect Matching > Directory Matching
    • The Servlet engine will call Servlet1.
  • When the request URL is "/ abc", both "/*" and "/ abc" match, which servlet responds
    • Perfect Matching > Directory Matching
    • The Servlet engine will call Servlet3.
  • When the request URL is "/abc/a.do", both "/abc/" and ".do" match, which servlet responds
    • Catalog Matching > Suffix Matching
    • The Servlet engine will call Servlet1.
  • When the request URL is "/a.do", both "/" and ".do" match, which servlet responds
    • Catalog Matching > Suffix Matching
    • The Servlet engine will call Servlet2.
  • When the request URL is "/xxx/yyy/a.do", both "/" and ".do" match, which servlet responds
    • Catalog Matching > Suffix Matching
    • The Servlet engine will call Servlet2.

tomcat/conf/web.xml in 4.4 Tomcat

 <servlet-mapping>
        <servlet-name>jsp</servlet-name>
        <url-pattern>*.jsp</url-pattern>
        <url-pattern>*.jspx</url-pattern>
    </servlet-mapping>
  • As long as the suffix name is jsp or jspx, the servlet content named jsp is executed, which is a typical extension matching effect.
   <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
  • At this point < url-pattern > its value is "/", then it is a default (default) servlet. The default servlet is used to handle requests that other servlets cannot handle.

5.load-on-satrtup

When we talked about the lifecycle of a servlet, the execution time of the init method is the default first access time. By configuring a servlet, we can change the execution time of the method.

5.1 Foundation

  • load-on-startup is a subtag under the servlet tag
  • Initialization time used to modify servlet s
  • Value is a positive integer, the smaller the value, the higher the priority.
  • Example:
     <servlet>
        <servlet-name>LifeServlet</servlet-name>
        <servlet-class>com.zqx.c_life.LifeServlet</servlet-class>
        <load-on-startup>3</load-on-startup>
    </servlet>
    
  • Effect
  • As you can see, the init method of LifeServlet is already invoked when the server starts
  • Suitable for starting a project, need to do some initialization operations, you can set up in this way

5.2 web.xml in Tomcat

5.2.1 Access to resources that do not exist in the project

  • First, an interesting example is when we access a path that has not been configured in a project in a browser.

  • Although 404 is returned, this page still has content and response messages. Who sent this content here? It's the tomcat server
  • So how does this process respond? How does the tomcat server complete this response?
  • Look at tomcat/conf/web.xml and find this section of configuration information:
 <servlet>
        <servlet-name>default</servlet-name>
        <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
        <init-param>
            <param-name>debug</param-name>
            <param-value>0</param-value>
        </init-param>
        <init-param>
            <param-name>listings</param-name>
            <param-value>false</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
  <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
  • When accessing a path, when the configuration file in the project does not specify the configuration, tomcat's web.xml is looked up.
  • This shows that there is a direct inheritance relationship between web.xml and tomcat's web.xml in the project. If it is not found, it will go to tomcat's web.xml.

5.2.2 Access index.html

  • Similarly, we haven't configured index, but we still access pages that can appear.
  • This is also because tomcat's web.xml configuration file helps to implement the configuration
<welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

6. Writing of Path

  • Relative Path
    • Current path:. / or not written
    • Upper level path:./
  • Absolute path:
    • Absolute path with host and protocol:
      • http://www.baidu.com
    • Absolute paths without hosts and protocols:
      • / servlet/hello is often used

Posted by Ilyes on Sat, 10 Aug 2019 05:08:09 -0700