Detailed explanation of Spring MVC DispatcherServlet

Features of Spring MVC

The Spring MVC framework is DispatcherServletdesigned around, which Servletdistributes requests to various processors and supports configurable processor mapping, view rendering, localization, time zone and theme rendering, and file uploading.

Handlers are classes and methods annotated with @Controllerand in an application, @RequestMappingand Spring provides a very diverse and flexible configuration for handler methods.

After Spring 3.0, @Controllerannotation mechanisms, @PathVariableannotations, and some other features are provided, which you can use to develop RESTful web sites and applications.

Spring MVC has the following features:

  • Clear separation of duties. Each role - controller, validator, command object, form object, model object, DispatcherServlet, handler mapping, view resolver, and many more - can be done by the corresponding object.
  • Powerful, intuitive framework and configuration of application beans. This configuration capability includes the ability to make simple references from different contexts, such as business objects, validators, etc. in web controllers.
  • Powerful adaptability, non-invasiveness and flexibility. Spring MVC allows you to define arbitrary controller method signatures, and in specific scenarios you can also add appropriate annotations (such as @RequestParam, @RequestHeader, , @PathVariableetc.)
  • Reusable business code keeps you away from duplicate code. You can use existing business objects as command objects or form objects without having them inherit from a framework-provided base class.
  • Customizable data binding and validation. Type mismatches are only considered application-level validation errors, and incorrect values, localized dates, numeric bindings, etc. are saved. You no longer need to use full String fields in form objects and then manually convert them to business objects.
  • Customizable handler mapping and view resolution. Handler mappings and view resolution strategies range from simple URL-based configuration to fine-grained specialized resolution strategies, all supported by Spring. In this regard, Spring is more flexible than some web frameworks that rely on specific technologies.
  • Flexible model delivery. Spring uses a Map of name/value pairs for the model, which makes the model easy to integrate and pass to any type of view technology.
  • Customizable localization information, time zone and theme parsing. Supports JSP technology with/without Spring tag library, supports JSTL, supports Velocity templates without additional configuration, etc. ;
  • A simple but powerful JSP tag library, commonly called Spring tag library, which provides support for some features such as data binding, theme support, etc. These custom tags provide maximum flexibility for marking up your code.
  • A JSP form tag library introduced in Spring 2.0. It makes writing forms in JSP pages much easier.
  • Added a bean type whose lifetime is only bound to the current HTTP request or HTTP session.

Workflow of DispatcherServlet

The Spring MVC framework is request-driven: all designs revolve around a central Servletpoint, which is responsible for dispatching all requests to controllers; and provides other functionality required for web application development. DispatcherServletSeamless integration with the Spring IoC container means that you can use any feature provided by Spring in Spring MVC.

The following figure shows the DispatcherServletworkflow of processing requests in Spring Web MVC, DispatcherServletwhich is actually a "front controller" design pattern:

Based on Spring Boot , Spring MVC can be used directly, unless there are very personalized requirements, the related configuration does not need to be manually configured.

Configuration of DispatcherServlet

DispatcherServletIn fact, it is one Servlet(it inherits from the HttpServletbase class), and it also needs to web.xmlbe declared in the configuration file of your web application. You need to map the request web.xmlyou want to DispatcherServlethandle to the corresponding URL in the file. This is the standard Java EE servlet configuration; the following code shows the DispatcherServletdeclaration of the pair and path mapping:

<web-app>
    <servlet>
        <servlet-name>example</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>example</servlet-name>
        <url-pattern>/example/*</url-pattern>
    </servlet-mapping>
</web-app>

In the above example, all /examplerequests with a path starting with will be processed with examplethe name DispatcherServlet.

In a Servlet 3.0+ environment, you can also configure the servlet container programmatically. The following is an example of such a code-based configuration, which web.xmlis equivalent to the configuration file defined above.

public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {
        ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet());
        registration.setLoadOnStartup(1);
        registration.addMapping("/example/*");
    }

}

WebApplicationInitializeris an interface provided by Spring MVC that will look up all your code-based configurations and apply them to initialize the web container for Servlet 3 and above. It has an abstract implementation AbstractDispatcherServletInitializerto simplify DispatcherServletregistration: you just need to specify its servlet mapping.

WebApplicationContext

In Spring MVC, each DispatcherServletholds its own context object WebApplicationContext, which in turn inherits all beans already defined in the root WebApplicationContextobject. These inherited beans can be overloaded in specific servlet instances, and in each servlet instance you can also define new beans under its scope.

1.png

DispatcherServletDuring the initialization process, Spring MVC will WEB-INFlook for a configuration file named [servlet-name]-servlet.xml in the directory of your web application and create the beans defined in it. If beans with the same name exist in the global context, they will be overwritten by newly defined beans with the same name.

The following DispatcherServletservlet configuration (defined in the web.xml file):

<web-app>
    <servlet>
        <servlet-name>golfing</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>golfing</servlet-name>
        <url-pattern>/golfing/*</url-pattern>
    </servlet-mapping>
</web-app>

With the above servlet configuration file, you also need to create a file /WEB-INF/under the path in the application, in which all Spring MVC related components (such as beans, etc.) are defined.golfing-servlet.xml

To customize DispatcherServletthe configuration, add some servlet initialization parameters (through init-paramelements) to the servlet declaration element. The list of optional parameters for this element is as follows:

Optional parameter explanation
contextClass Any WebApplicationContextclass that implements an interface. This class initializes the context object that the servlet needs to use. By default, the framework uses an XmlWebApplicationContextobject.
contextConfigLocation A string specifying the path to the context configuration file that will be passed to contextClassthe specified context instance object. This string can contain multiple strings, separated by commas, so that you can configure multiple contexts. For beans defined repeatedly in multiple contexts, the last bean definition loaded takes precedence
namespace WebApplicationContextnamespace. Default is[servlet-name]-servlet

Implementation of Spring MVC: Built-in Components in WebApplicationContext

WebApplicationContextInherited from ApplicationContext, it provides some features that are often used in web applications. WebApplicationContextis bound in ServletContext. If you need to get it, you can RequestContextUtilsget the context of this web application through the static method in the utility class WebApplicationContext.

Spring uses specific beans DispatcherServletbuilt in to handle requests, render views, etc., which are part of the Spring MVC framework. WebApplicationContextIf you want to specify which specific beans to use, you can WebApplicationContextsimply configure them in . Of course this is only optional, Spring MVC maintains a default list of beans, if no special configuration is made, the framework will use the default beans. DispatcherServletThese beans are depended on as shown in the following table.

bean type role
HandlerMapping Processor mapping. It maps incoming container requests to specific processors and a series of pre-processors and post-processors (ie, processor interceptors) according to certain rules. The exact rules vary depending HandlerMappingon the implementation of the class. One of its most common implementations allows you to add annotations to controllers to configure request paths. Of course, other implementations also exist.
HandlerAdapter processor adapter. After getting the handler corresponding to the request, the adapter will be responsible for calling the handler, which makes it DispatcherServletunnecessary to care about the specific calling details. For example, if you want to call a controller based on annotation configuration, you need to parse some corresponding information from many annotations before calling. Therefore, HandlerAdapterthe main task is to DispatcherServletshield these specific details.
HandlerExceptionResolver Handler exception parser. It is responsible for mapping caught exceptions to different views, and also supports more complex exception handling code.
ViewResolver View resolver. It is responsible for mapping a string (String) representing the logical view name to the actual view type View.
LocaleResolver & LocaleContextResolver Locale resolver and locale context resolver. They are responsible for parsing the client's region information and even time zone information, providing support for internationalized view customization.
ThemeResolver Topic parser. It is responsible for parsing the themes available in your web application, for example, providing some customized layouts, etc.
MultipartResolver Parse multi-part transmission requests, such as supporting file uploads through HTML forms, etc.
FlashMapManager FlashMap manager. It can store and retrieve FlashMapobjects between requests. The latter can be used to pass data between requests, usually in the context of request redirection.

This list of beans is kept in a file org.springframework.web.servletunder the package. DispatcherServlet.propertiesThese beans have some basic default behavior. Some of the default configurations they provide may need to be customized in the future. For example, it is often necessary to configure InternalResourceViewResolverthe properties provided by the class prefixto point to the directory where the view files are located.

WebApplicationContextOnce you configure a particular bean in the web application context (for example InternalResourceViewResolver), it overrides the default implementation of that bean. For example, if you configure the default implementation that InternalResourceViewResolverthe framework will no longer use .ViewResolver

Configuring Spring MVC can be configured through Java programming configuration or through the MVC XML namespace. Without going into details, you can refer to Spring MVC Configuration .

DispatcherServlet processing flow

After the configuration is complete DispatcherServlet, requests will begin to pass through this DispatcherServlet. At this point, DispatcherServletrequests are processed in the following order:

  • First, search for the application's context object WebApplicationContextand bind it as an attribute to the request so that controllers and other components can use it. The key name of the property defaults toDispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE
  • Bind a locale resolver to a request so that other components can get locale-related information when processing the request (rendering views, preparing data, etc.). If your app doesn't need to parse locale-related information, just ignore it
  • Bind a theme resolver to the request so that other components (like views, etc.) can know which theme file to render. Again, if you don't need to use theme-related features, just ignore it
  • If you configure a multipart file handler, then the framework will look to see if the file is multipart (multipart sequential uploads). If so, wrap the request into an MultipartHttpServletRequestobject for further processing by other components in the processing chain.
  • Find a suitable handler for the request. If a corresponding processor can be found, the entire execution chain associated with that processor (pre-processor, post-processor, controller, etc.) is executed to complete the preparation of the corresponding model or rendering of the view
  • If the handler returns a model, the framework will render the corresponding view. If no model is returned (probably because the previous and subsequent processors intercepted the request for some reason, such as security issues), the framework will not render any views, and it is believed that the processing of the request may have been completed by the processing chain span

If exceptions are thrown during the processing of the request, WebApplicationContextthe exception handler defined in the context object will be responsible for catching those exceptions. By configuring your own exception handler, you can customize the way you handle exceptions.

Spring DispatcherServletalso allows the handler to return a last-modification-date value as defined in the Servlet API specification. The way to determine the last modification time of a request is straightforward: DispatcherServletit looks for the appropriate handler map to find the handler for the request, and then checks to see if it implements the LastModified interface. If so, call the long getLastModified(request)method of the interface and return the return value to the client.

 

https://www.tianmaying.com/tutorial/spring-mvc-DispatcherServlet

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327004484&siteId=291194637