3. Process HTTP requests in Web applications
After traversing the Web container, the HTTP request is delivered to the Web application, and we continue with the Tomcat example. The interface between the Web container and the Web application is done through the configuration file web.xml. Web. XML is a configuration file that follows the Java Servlet standard specification. This configuration file defines the various core components and initial configurations that make up a Web application, including filters, listeners, server servlets, and so on. Different components perform different functions, and as usual, we take a look at these core components before introducing the flow of Web applications handling HTTP requests.
3.1 Introduction to Core Components of Web Applications
3.1.1 Filter Filter
The Filter preprocesses the HTTP request, then passes the request to the Servlet for processing and generating the response, and finally the Filter postprocesses the response. In terms of HTTP request processing, Filter mainly participates in the following links:
- Intercepts the client’s HttpServletRequest until it reaches the Servlet.
- Check the HttpServletRequest as needed and modify the HttpServletRequest header and data.
- Intercepts HttpServletResponse until the servlet-generated HttpServletResponse reaches the client.
- Check the HttpServletResponse as needed and modify the HttpServletResponse header and data as well.
Filter-mapping is used to declare the filters used by Web applications. The filters can be mapped to a Servlet or URL mode. If a filter is mapped to a Servlet, it works on a specific Servlet. If you map a filter to a URL pattern, it will work on any resource whose URL matches the URL pattern. If multiple filters are matched for a resource, Tomcat executes the filter-mapping in the configuration file web. XML in order to process HTTP requests. The preceding Filter mapping is executed first, and the subsequent Filter mapping is executed later. Multiple filters can form a chain of calls. There are three types of rules for URL pattern matching:
- Exact matches: such as “/foo.htm”, which will only match the URL “foo.htm”.
- Path matching: “/foo/*”, for example, will only match urls prefixed with foo.
- Suffix matching: For example, “*.htm” will only match all urls with the suffix “.htm “.
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Copy the code
3.1.2 Listener
The Listener is used to monitor the changes of Application objects, Session objects, Request objects, etc. Whenever these objects change, the corresponding listening method will be called back. For example, there is a ServletContextListener interface in the Servlet API that listens for the life cycle of a ServletContext object, essentially the life cycle of a Web application. When the Servlet container starts or terminates the Web application, the ServletContextEvent event is emitted, which is handled by the ServletContextListener.
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
Copy the code
3.1.3 Server Servlets
Server servlets handle HTTP requests from clients to access dynamic resources. The interface javax.servlet. servlets define the methods that all servlets must implement.
Method names | Functional specifications |
---|---|
destroy() | Called by the Servlet container to shut down and stop services provided by servlets |
getServletConfig() | Gets the configuration information object ServletConfig for Servlet initialization and startup parameters |
getServletInfo() | Get description information for the Servlet, including author, version, copyright, and so on |
init() | Called by the Servlet container, the Servlet is initialized by configuring ServletConfig to start the external service |
service() | Called by the Servlet container to let the Servlet process an HTTP request |
In terms of HTTP request processing, server servlets participate in the following steps:
- Receive the request: The client request is encapsulated into an HttpServletRequest object containing information such as header parameters and message style.
- Request processing: Usually call Servlet methods such as Service, doPost or doGet to process the request, and further call the corresponding logic of the business layer to process it, etc.
- Feedback: After a request is processed, it can be forwarded, redirected to a view page, or returned directly to the resulting data. Forwarding is HttpServletRequest, and redirection is HttpServletResponse.
In veteran brother’s school days, Web applications were relatively simple, mainly a variety of information management systems. At that time, Spring had not yet been born, and the mainstream technology stack was JSP/Servlet. When I developed Web applications, I mainly wrote subclasses of HttpServlet to inherit from them, and implemented various business logic functions by different subclasses of HttpServlet. HttpServlet inherits from GenericServlet, which implements the interface Servlet. With the continuous advancement of digitization and Internet, business system becomes more and more complex, the subclass of HttpServlet is more and more written, web. XML configuration file is more and more complex, which leads to the expansion and maintenance of the system is more and more difficult, manual workshop development method has been unable to keep up with the pace of business development. It is in this context that Spring comes up with the creative invention of inversion of control IOC and section-oriented programming AOP to greatly reduce complexity. As shown in the following configuration example, the entire Web application only needs to be configured with one Servlet, which is Spring’s pre-dispatcherServlet:
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/api</url-pattern>
</servlet-mapping>
Copy the code
3.2 Process of Web Applications processing HTTP Requests
As shown in the following figure, a Web application processes an HTTP request through a Listener and a chain of Filters to reach a server Servlet:
After Tomcat receives Http requests from a Web application, it forwards all requests to the pre-dispatcher DispatcherServlet, which then sends the requests to the specific business logic for processing. DispatcherServlet is a subclass of HttpServlet and its class diagram is as follows:
3.3 Web Application Architecture Evolution
The evolution of Web application architecture is similar to the incubation process. At the beginning, the startup team built a simple product and adopted the manual workshop model to quickly build a minimum viable product. At this time, the organizational structure of the team was as flat and simple as the product. But as the product is used by more and more users, the functionality becomes more complex, and new architectures must be introduced to manage complexity effectively, while the expansion of team size requires an organizational structure that matches the growth of the business so that the product can continue to grow. The evolution process of Web application architecture is similar to the formation process of Tomcat architecture. Veteran brother often uses the Model of “Russian nesting doll” to explain architecture. The architectural principles of the two layers of Web container and Web application are similar, just like the big doll covers the small doll.
The IOC container of Spring is similar to the Servlet container of Tomcat. Components are defined through configuration files and other means. These defined components are initialized and added to the container during startup, and obtained from the container for subsequent use. Early Web applications are mainly composed of Filter\Listener\Servlet and other components written by a large number of developers. The configuration of these core components are all maintained through the web. XML configuration file, so the Web application and Web container are not loosely coupled. After the introduction of Spring, only a small number of components such as DispatcherServlet need to be configured, which has reached the requirements of hierarchical architecture and is more conducive to the development of complex Web applications. In architectural terms, this is the classic layered architecture pattern, with loose coupling between layers, only a few interfaces, and high cohesion within each layer.
The main value of this article is to help you sort out the end-to-end process framework, which is often referred to as the global or God perspective. With this framework, we can look for related node information according to our own needs to study and learn, so as not to get lost in details. Of course, considering that each of us has different work and study situations, and the problems we encounter are also different, the content of this article cannot cover all the problems we encounter, please leave your comments and ask questions.
Today first share here, if you feel valuable, please move your finger to forward to other partners in need. In addition, I will share my experience in career planning, job interviews, skills improvement and influence building in the future. Please pay attention to this column or “IT veteran brother”!
Other articles in this series are indexed below:
- Spring: HTTP Request Processing flow and mechanism [1]
- Spring: HTTP Request Processing and mechanism [2]
- Spring: HTTP Request Processing flow and mechanism [4]
- Spring: HTTP Request Processing flow and mechanism [5]
- Spring: HTTP Request Processing flow and mechanism [6]