Module a required foundation

01 Essential knowledge of the HTTP protocol

HTTP Request Process

  1. The user performs an action through the browser, such as typing a url and hitting enter, or clicking on a link, and the browser retrieves the event.
  2. The browser sends a TCP connection request to the server.
  3. The service program accepts the browser’s connection request and establishes the connection through the TCP three-way handshake.
  4. The browser packages the request data into an HTTP protocol format.
  5. The browser pushes the packet to the network, where it travels to the server.
  6. After receiving the packet, the server program unpacks the packet in THE HTTP protocol format to obtain the intent of the client.
  7. When the client intent is known, process it, such as providing a static file or calling a server program to get a dynamic result.
  8. The server packages the response, which can be HTML or images, in the HTTP protocol format.
    1. The server pushes the response packet over the network, where it travels to the browser.
  9. The browser takes the packet, unpacks it in HTTP format, and then parses the data, which in this case is HTML.
  10. The browser displays HTML files on the page.
HTTP request response instance

Request: request line, request header, request body Response: status line, response packet, message body

The cookie and session

A Cookie is essentially a file stored locally to the user that contains information that needs to be passed on each request

Session can be understood as the storage space opened up by the server side, which saves the state of the user

When a user request arrives, the server can match the user’s request to the user’s Session. So how does Session correspond to request? The answer is through a Cookie, where the browser fills in a field like a Session ID to identify the request.

Understanding the restful style

Think of the information entity on the network as a resource. It can be a picture, a file, a service… A resource is identified by a URI. There is no verb in a URI, because it is the identifier of the resource. How to operate on the resource? To manipulate a resource via URI+ action.

Understanding of Http stateless requests

In order to complete an operation, the request contains all the information. You can understand that the server does not need to save the state of the request, that is, it does not need to save the session. The benefit of not having a session is that the server has good scalability and facilitates failover. Requests are routed by the LB to different server instances with no difference. From this perspective, the stateless nature of HTTP is the result of the REST architectural style, which, by the way, is from the same author as HTTP1.1. But while the ideal is full, the reality is thin, and most complex Web applications have to keep sessions on the server for ease of development. In order to minimize the disadvantages of sessions, sessions are stored centrally on Redis rather than directly on the server instance.

An understanding of HTTP persistent connections and the differences between 1.0 and 1.1 and 2.0

In THE HTTP/1.0 era, a new TCP connection was created for each HTTP request and closed after the request was completed. HTTP/1.1 introduced the concept of HTTP persistent Connection. Using the HTTP protocol of persistent Connection, the response header is added with Connection:keep-alive. In this way, when the browser completes a request, the TCP connection between the browser and the server is not closed, and the browser continues to use the established connection when the web page on the server is accessed again, which means that two requests may share the same TCP connection. In HTTP/1.1, the head of line blocking problem is still not solved. Later connections must wait for the return of the previous connection before they can be sent. This problem was not completely solved until HTTP/2.0 adopted binary frame coding.

02. Servlet specifications and Servlet containers

Relationship between servlets and servlet containers

A Servlet is essentially an interface. Business classes that implement the Servlet interface are also called servlets. A Servlet interface is an interface between a Servlet container and a specific Servlet business class. The whole set of specifications for the Servlet interface and Servlet container is called the Servlet Specification, and the Servlet specification allows programmers to focus on the development of business logic, while the Servlet specification provides developers with extended mechanisms, Filter and Listener.


public interface Servlet {
    void init(ServletConfig config) throws ServletException;
    
    ServletConfig getServletConfig(a);
    
    void service(ServletRequest Req, ServletResponse res)throws ServletException, IOException;
    
    String getServletInfo();
    
    void destroy(a);
}
Copy the code
Servlet container engineering process

  1. When a client requests a resource, the HTTP server encapsulates the client’s request information with a ServletRequest object
  2. Then call the Servlet container’s service method, Servlet container gets the request, according to the request URL and Servlet mapping relationship, to find the corresponding Servlet
  3. If the Servlet is not already loaded, create the Servlet using the reflection mechanism and call the init method of the Servlet to complete the initialization
  4. The Servlet’s service method is then called to process the request, returning the ServletResponse object to the HTTP server, which sends the response to the client.
What is the ServletContext

The Servlet specification defines the ServletContext interface for a Web application. Once the Web application is deployed, the Servlet container loads the Web application at startup and creates a unique ServletContext object for each Web application. You can think of a ServletContext as a global object. A Web application might have multiple servlets that share data through a global ServletContext. The data includes the initialization parameters of the Web application and file resources in the Web application directory. Since ServletContext holds all Servlet instances, you can also use it to forward Servlet requests.

What is the Filter

Filter is an interface that allows you to customize requests and responses uniformly. For example, you can restrict access based on the frequency of the request, or modify the response by country or region. Here’s how filters work: After the Web application is deployed, the Servlet container needs to instantiate the Filter and link the Filter into a FilterChain. When the request comes in, it gets the first Filter and calls the doFilter method, which is responsible for calling the next Filter in the FilterChain.

What is the Listener

A Listener is another extension mechanism. When the Web application runs in the Servlet container, various events will occur continuously inside the Servlet container, such as the start and stop of the Web application, the arrival of user requests, etc. The Servlet container provides some default listeners to listen for these events, and the Servlet container is responsible for calling the listener’s methods when the event occurs. Of course, you can define your own listeners to listen for events of interest to you by configuring them in web.xml. Spring, for example, implements its own listener to listen for the start event of the ServletContext in order to create and initialize the global Spring container when the Servlet container starts.

The relationship between the Filter and the Listener and the intercepter

1.Filter is part of the Servlet specification and is implemented by the Servlet container Tomcat. 2. The Intercepter was invented by Spring. 3. They are executed in the order filter.dofilter (); HandlerInterceptor.preHandle(); The Controller; HandlerInterceptor.postHandle(); DispatcherServlet render view HandlerInterceptor. AfterCompletion (); Filter.doFilter(); Servlet method returns;

A Filter is an intervention, part of a process, and based on process behavior. The Listener is state-based, and any behavior that changes the same state triggers the same event.

The relationship between the Servlet container and Spring container and the SpringMVC container

The Servlet container is used to manage the Servlet lifecycle. The Spring container is used to manage the Life cycle of Spring beans, such as services, DAOs, etc. SpringMVC container for managing the SpringMVC Bean lifecycle, such as Controller, ViewResovler, etc.

Tomcat/Jetty starts and initialises each WebApp in turn:

  1. For each WebApp, there is a WebApp ClassLoader and a ServletContext

  2. When ServletContext starts, it scans the Web. XML configuration file to find Filter, Listener, and Servlet configurations

  3. If the Listener is equipped with spring’s ContextLoaderListener

    • The ContextLoaderListener receives various webApp state information.
    • When the ServletContext is initialized, the Spring IOC container is initialized by ContextLoaderListener to manage the Spring-related beans.
    • ContextLoaderListener stores the Spring IOC container in the ServletContext
  4. If you have SpringMVC’s DispatcherServlet in your Servlet

    • When the DispatcherServlet is initialized (its first request arrives at initialization, lazy loading).
    • The DispatcherServlet initializes its own SpringMVC container to manage The Beans associated with SpringMVC.
    • The SpringMVC container can get the Spring container from the ServletContext and set the Spring container as its root container. The child container can access the parent container, so it can access the Service object in the Controller, but it cannot access the Controller object in the Service.

Figure blog.csdn.net/zhanglf02/a a description relationship…

Create a Servlet by hand

Basic steps
  1. Download and install Tomcat.
  2. Write a Java class that inherits HttpServlet.
  3. Compile Java Class files into Class files.
  4. Create a directory structure for the Web application and configure web.xml.
  5. The Web application is deployed.
  6. Start Tomcat.
  7. Browser access verification result.
  8. View Tomcat logs.
catalogue
  1. /bin: stores the script files for starting and closing Tomcat on Windows or Linux.
  2. /conf: holds the various global configuration files for Tomcat, the most important of which is server.xml.
  3. /lib: Stores JAR files accessible to Tomcat and all Web applications.
  4. /logs: stores log files generated during Tomcat execution.
  5. /work: Store the Class file generated after the JSP compilation.
  6. /webapps: Tomcat Web application directory. By default, Web applications are placed in this directory.
Log Directory

This section briefly describes the meanings of each file.

  1. Catalina.xxx. log records information about the Tomcat startup process. In this file, you can view log information such as JVM parameters and operating system.
  2. Catalina.outcatalina.out is the Standard output (stdout) and standard error (stderr) of Tomcat, which are specified in the Tomcat startup script. If not modified, stdout and stderr will be redirected here. So in this file you can see the information we printed in myservlet.java: MyServlet is handling get requests…
  3. Localhost.xx. log records the unhandled exceptions encountered during the initialization of the Web application. Tomcat catches the exceptions and outputs this log file.
  4. Localhost_access_log.xx. TXT Stores logs about Tomcat access requests, including the IP address, request path, time, request protocol, and status code.
  5. Manager.xxx. log/host-manager.xxx.log Stores logs of the Tomcat manager project.
Web. XML configuration and @WebServlet annotation configuration

The following two configurations can inject servlets into the servlet container

 <servlet>      
     <servlet-name>myServlet</servlet-name>      
     <servlet-class>MyServlet</servlet-class>   
 </servlet>    
 <servlet-mapping>     
     <servlet-name>myServlet</servlet-name>   
     <url-pattern>/myservlet</url-pattern>   
 </servlet-mapping>
Copy the code
@WebServlet("/myAnnotationServlet")
public class AnnotationServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    //TODO
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    //TODO

}  
Copy the code
Pay attention to

Service method is defined in Servlet interface, no doGet/doPost. HttpServlet is an implementation class that implements the Service method while leaving the doGet/doPost method for the programmer to implement.

note

This article is my personal study of Li Haoshuang’s column course, combined with the column articles and the teacher’s questions to students organized study notes. For sharing only. For more exciting content, you can scan the below two codes, and subscribe to Li Jishuang’s In-depth Dismantling of Tomcat & Jetty during geek time. Obtain first-hand learning materials.