Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the request distribution mechanism from Servlet to Spring?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "what is the request distribution mechanism from Servlet to Spring". In daily operation, I believe many people have doubts about what the request distribution mechanism from Servlet to Spring is. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "what is the request distribution mechanism from Servlet to Spring". Next, please follow the editor to study!

Before you talk about request distribution, comb through the interaction logic of an Web request:

First, the user sends a request from the client to the server.

The request is first parsed by the operating system's TCP/IP protocol stack and sent to a port.

There is a Web application server running on this port (assuming Tomcat)

Then Tomcat will send the request to the corresponding Servlet according to the request path for processing.

(note that the Web server itself does not process requests, such as Tomcat, which is only responsible for distributing requests.)

Request distribution during the 1.Servlet period

When there is no spring framework, you can only use Servlet to process requests.

The specific approach is: configure Servlet and its mapping path in a configuration file called web.xml, when the server starts, Tomcat will automatically read this file, and then assign the request to the corresponding Servlet according to the configuration in the file.

At this time, the work of requesting distribution is done in Tomcat, usually a business corresponds to a Servlet. For example, with regard to the addition, deletion, modification and query of users, the corresponding Servlet is likely to look like this:

AddUserServlet

DeleteUserServlet

UpdateUserServlet

...

The corresponding structure diagram is as follows:

This is very different from the architecture we are developing today, because now it is usually a class that contains all the processing logic for the same business. For example, the additions, deletions, changes and queries of users are all put in the same class and distinguished in different ways.

But in the past, only one service in a Servlet was useful, and other lifecycle-related methods were basically just a rewrite of an empty shell, so a service method corresponds to a business processing logic. This classification method not only brings a great burden to the web server, but also leads to a large number of web.xml files. (the addition, deletion, modification and query logic of User corresponds to 4 Servlet. It would be nice to distribute the processing logic related to User to a large UserServlet.)

Then someone found a way to distribute the processing logic related to User to a large UserServlet. The way to do this is to use reflection in Java. The detailed code is as follows:

/ * *

* the Servlet does not need to be configured because the Servlet never needs to be accessed directly and is used to be inherited

* can be defined as abstract class

, /

Public abstract class BaseServlet extends HttpServlet {

@ Override

Protected void service (HttpServletRequest request, HttpServletResponse response)

Throws ServletException, IOException {

/ / solve the problem of garbled code in post form

Request.setCharacterEncoding ("utf-8")

/ / get the value of the method property (method name)

String methodName = request.getParameter ("method")

If (methodName = = null | | methodName.trim () .isEmpty ()) {

Throw new RuntimeException ("you did not pass a method parameter! cannot determine the method you want to call!")

}

/ / call the method using reflection

Try {

/ / get the Class information of the current Servlet

Class clazz = this.getClass (); / / the Servlet actually visited is not BaseServlet, but a subclass of BaseServlet, such as UserServlet

/ / create objects using reflection

/ / Object obj = clazz.newInstance ()

/ / acquisition method

Method method = clazz.getMethod (methodName, HttpServletRequest.class,HttpServletResponse.class)

/ / use reflection to execute the method

Method.invoke (this, request,response)

} catch (Exception e) {

E.printStackTrace ()

}

}

}

As a result, the structure of the distribution request looks like this:

In other words, requests for similar services are assigned to the same Serlvet, when specific to the subdivided business logic, different methods are used to distinguish; at run time, reflection is used to call specific methods.

Doing so significantly reduces the pressure on the server to distribute requests and makes the web.xml file more concise. And the same type of business logic can be written in the same class to facilitate management and maintenance. But is it possible to do better?

Request distribution of the 2.Spring framework

First, use a picture to describe the request distribution of the Spring framework. The picture is easy to understand:

You can see from the figure that the web server doesn't have to think about distributing the request at this point, it just needs to send the request to DispatcherServlet. The task of requesting distribution will fall on DispatcherServlet.

Instead of distributing the request to other Servlet, DispatchServlet distributes the request to the corresponding Controller according to the request path, and then distributes it to the corresponding processing method in Controller.

Here is a mini abbreviated version of the DispatchServlet code:

Public class DispatcherServlet implements Servlet {

@ Override

Public void init (ServletConfig servletConfig) throws ServletException {}

@ Override

Public ServletConfig getServletConfig () {

Return null

}

@ Override

Public void service (ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {

For (MappingHandler mappingHandler: HandlerManager.mappingHandlerList) {

Try {

If (mappingHandler.handle (servletRequest, servletResponse)) {

Return

}

} catch (IllegalAccessException e) {

E.printStackTrace ()

} catch (InstantiationException e) {

E.printStackTrace ()

} catch (InvocationTargetException e) {

E.printStackTrace ()

}

}

}

@ Override

Public String getServletInfo () {

Return null

}

@ Override

Public void destroy () {}

}

From the above code, you can see that the logic for DispatcherServlet to process the request is also very simple, which is to find the corresponding processor that can be processed according to the request path.

As for how MappingHandler is initialized, this involves knowledge of control inversion and dependency injection in the Spring framework. To put it simply, during the development process, we no longer configure the request path in web.xml, but annotate it at the top of each processing method. When the spring framework is started, each processing method is initialized into MappingHandler (including request path and processing logic) according to the annotations for DispatcherServlet provisioning.

This kind of request distribution is undoubtedly more flexible and powerful than the request distribution in the period of Serlvet. It migrates the work of requesting distribution from the web server to the framework and is more scalable. And with the control inversion mechanism of the spring framework, the initialization and life cycle control of the processing logic class are handed over to the framework management, which is more secure and efficient.

At this point, the study on "what is the request distribution mechanism from Servlet to Spring" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report