Java-Servlet parsing

foreword

I have been engaged in the development of Javaweb projects for a while, and I have never understood what it is all about. Later, I checked the information and found that there are several things involved, namely tomcat, servlet, one of the 13 specifications in JavaEE, and springMVC. So I went to study and found that there are operations around this servlet. So there is today's summary.

Servlet

definition

Servlet (Server Applet) is the abbreviation of Java Servlet, which is called a small service program or a service connector. It is a server-side program written in Java and has the characteristics of being independent of platforms and protocols. Dynamic web content.
A Servlet in a narrow sense refers to an interface implemented by the Java language, and a Servlet in a broad sense refers to any class that implements the Servlet interface. Generally, people understand Servlet as the latter. ServletRuns on an application server that supports Java. In principle, Servlets can respond to any type of request, but in most cases Servlets are only used to extend the base HTTP协议的Web服务器.
There are many kinds of web servers, among which tomcat, Netty, and Microsoft's IIS (Internet Information Services) are commonly used. The
web server used in this article istomcat

internal analysis

Since this servlet is a specification, generally speaking, the specification is an interface, just like in the project development process, the front-end development engineer and the back-end development engineer develop according to the interface document, and both sides abide by this interface document , then the development process will reduce a lot of unnecessary trouble. So the following figure is Servletthe structure display in Java.

image.png

package javax.servlet;
public interface Servlet {
    
    
    void init(javax.servlet.ServletConfig servletConfig) throws javax.servlet.ServletException;
    javax.servlet.ServletConfig getServletConfig();
    void service(javax.servlet.ServletRequest servletRequest, javax.servlet.ServletResponse servletResponse) throws javax.servlet.ServletException, java.io.IOException;
    java.lang.String getServletInfo();
    void destroy();
}

The following is a display of the internal methods of the servlet interface. There are 5 methods in total.

  • The first init(javax.servlet.ServletConfig servletConfig)
    method is executed when the servlet object is initialized, only once.
  • The second getServletConfig()
    method obtains the parameters configured in web.xml such as:
    image.png
  • The third service(javax.servlet.ServletRequest servletRequest, javax.servlet.ServletResponse servletResponse)
    service method is very important. This method is the request interface method we will use. In layman’s terms, we can put our business code in this service method in the web project. When we are in the project After the servlet mapping is configured in the servlet, the request is called, and tomcat calls this method. It will be demonstrated in detail later. In actual development, instead of directly implementing the servlet interface, the doGet and doPost methods in the HttpServlet class are rewritten.
  • Fourth, getServletInfo()
    when the Servlet container (such as Tomcat) needs to provide information about the Servlet, it will call the getServletInfo() method. Typically, this information is used to manage and monitor the deployment and execution of Servlets. For example, when an administrator views an application deployed in a Servlet container, information such as the Servlet's name, description, and version number may be displayed.
  • Fifth destroy(),
    when the Servlet container (such as Tomcat) needs to close or uninstall the Servlet, it will call the destroy() method of the Servlet. This usually occurs in the following situations:
    Server shutdown: When the server is shut down or restarted, the Servlet container will notify all running Servlets to perform a destruction operation to ensure that they can properly release resources.
    Servlet is unloaded: When the Servlet of the application is unloaded from the Servlet container, the container will call the destroy() method first, and then the Servlet will be removed from the container.
    In the destroy() method, the servlet can perform some cleanup tasks, such as releasing open files, closing database connections, unregistering listeners, etc. This is an important time for resource cleanup and release to ensure a graceful shutdown of the application and proper release of resources.

Summarize the servlet interface

The above content is the method defined in the servlet interface of JavaEE. These methods initwill destroyonly be executed once, that is to say, when the tomcat program starts, these two methods in the servlet will only be called once, respectively to create the servlet object And when destroying the servlet, then everyone will definitely ask, since it is only called once, who called it? The answer is web容器去调用的that the code we write in the web project is finally executed by tomcat, but how does tomcat know which methods of your classes to call? In order to solve this problem, there is this servlet specification. Tomcat only pays attention to these classes that implement the servlet interface, and it will not call other classes.

The servlet for the actual application

The above summary said that the servlet is called by tomcat, that is to say, as long as the code we write ourselves implements the servlet interface and configures it in web.xml, then when tomcat starts, it will call us Write your own servlet to create objects.
However, in actual application, the servlet class we wrote by ourselves did not directly implement the servlet but inherit the abstract class. HttpServletHere, everyone has doubts. Why should we inherit an abstract class instead of directly implementing the servlet interface? Woolen cloth? Here I need to tell you about a structural diagram (class diagram relationship) of the servlet we released at the beginning.image.png

GenericServlet class and HttpServlet class

GenericServletClass and HttpServletclass are two important classes in Java Servlet API, which are used to realize the basic functions of Servlet.

  1. GenericServletkind:

    • GenericServletIt is an abstract class that implements Servletthe interface.
    • It provides the basic implementation of Servlet, which can be inherited and used to create custom Servlets.
    • GenericServletApplicable to all types of protocols, not limited to HTTP protocol.
    • It simplifies the writing of Servlet, by providing a default empty implementation, so that developers only need to rewrite the methods of interest.
    • GenericServletThe most important method is service()that used to handle client requests. By default, it delegates to methods such as doGet(), doPost()etc., which can be overridden in subclasses to implement specific request handling logic.
    • In addition to service()methods, GenericServletother useful methods, such as getServletConfig()and getServletInfo(), are provided to obtain Servlet configuration information and description information.
  2. HttpServletkind:

    • HttpServletIt is GenericServleta subclass that is specially used to handle requests based on the HTTP protocol.
    • It is extended GenericServletto provide methods and functions for more convenient handling of HTTP requests.
    • HttpServletBy rewriting doGet(), doPost(), doPut()and other methods, the corresponding processing logic can be executed according to the request type.
    • It also provides a series of hook methods (such as doHead(), doDelete(), doOptions()etc.) for handling specific HTTP request methods.
    • HttpServletIt also provides some auxiliary methods for handling HTTP requests, such as obtaining request parameters, handling sessions and cookies, etc.

To sum up, GenericServletthe class is a general Servlet base class, applicable to various protocols. The class HttpServletis GenericServletbased on providing more convenient processing methods and functions for the HTTP protocol. In general, when developing a Servlet based on the HTTP protocol, HttpServletthe class should be used as the base class in order to better handle HTTP requests and provide corresponding functions.
The http protocol is basically used in web projects, so the servlet classes we write ourselves inherit the HttpServlet class, because this class helps us do the corresponding http protocol analysis.

Design Patterns in HttpServlet

Since the http protocol is used for communication, the requests of the http protocol are of different types, such as post, get, put, etc. How do these types of request servlets distinguish? Because there is only one service method in the servlet interface that will be called by tomcat! So the behavioral one in the design pattern is used here 模板方法.

First look at the definition of the template method

  • Template Method Pattern (Template Method Pattern), also known as Template Pattern (Template Pattern), refers to a template that publicly defines the method to execute it in an abstract class. Its subclasses can override the method implementation as needed, but calls will be made in the manner defined in the abstract class.
  • Simply put, the template method pattern defines the skeleton of an algorithm in an operation, and defers some steps to subclasses, so that subclasses can redefine some specific steps of the algorithm without changing the structure of an algorithm.

image.png

step by step analysis

Methods corresponding to different types of requests are defined in HttpServlet

  • doGet, if the servlet supports HTTP GET requests
  • doPost, for HTTP POST requests
  • doPut, for HTTP PUT requests
  • doDelete, for HTTP delete requests
    image.png
    , as long as it inherits HttpServlet and rewrites the above different methods, it can call the corresponding method when there is a corresponding type of request. Then everyone will definitely think, how does it know what request I made when I request this servlet with so many methods? Let me talk about it here. This HttpServlet has already parsed the http request, that is to say, it has parsed what type the request is. When it parses that the request is of the post type, it will call the method. How does it call it doPost? Here comes the core of the template method, defining the algorithm skeleton. There is a method called method in HttpServlet service. This method is not the method of the implemented servlet interface service. There is a difference between the two.
    image.png
  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) {
    
    
                // servlet doesn't support if-modified-since, no reason
                // to go through further expensive logic
                doGet(req, resp);
            } else {
    
    
                long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
                if (ifModifiedSince < lastModified) {
    
    
                    // If the servlet mod time is later, call doGet()
                    // Round down to the nearest second for a proper compare
                    // A ifModifiedSince of -1 will always be less
                    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 {
    
    
            //
            // Note that this means NO servlet supports whatever
            // method was requested, anywhere on this server.
            //

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

image.png
So when the class we wrote inherits HttpServlet and then renews the doPost or doGet methods in it, it will be distributed in the custom service method in HttpServlet. You can look at
image.png
this service method. There is a service method call, which is in Call the custom service method in HttpServlet for subsequent request distribution.
image.png

Spring MVC application

Speaking of which, let me briefly talk about it. The implementation of SpringMVC is based on the Servletimplementation. When configuring the mvc project, using springMVC needs to be configured in web.xml. You can take a look at what this configuration is.
image.png
Continue to look down, let's take a look at the core classes in SpringMVC DispatcherServlet, and we can see that this class actually implements Servletthe interface. That is to say, the implementation of SpringMVC is developed based on Servlet.
image.png

Guess you like

Origin blog.csdn.net/pengjun_ge/article/details/130815566