preface

As Spring Boot has moved into full coverage of our projects, we have largely forgotten the classic Servlet + Spring MVC combination of the familiar web.xml configuration. In this article, we want to take a step back from Spring Boot and see how servlets integrate with Spring MVC to initialize the Spring container.

  • Spring MVC overview

  • Annotation-driven controller

  • Handles the data binding of methods

  • Try and view resolver

  • localization

  • File upload

  • WebSocket

  • Static resource processing

  • The interceptor

  • Exception handling

Overview of Spring MVC

MVC: Model + View + Controller (Data Model + View + Controller)

Three layer architecture

Three-tier architecture: Presentation Tier + Application Tier + Data Tier (Presentation tier + Application tier + Data access tier)

MVC and three-tier architecture

The relationship between MVC and three-tier architecture. MVC only has the presentation layer of three-tier architecture.

M is actually the data model, the object that contains the data. In Spring MVC, there is a special class called Model for data interaction and value transfer with V. V refers to the view interface, which includes JSPS, freeMarker, Velocity, Thymeleaf, Tiles, etc. C is the Controller (Spring MVC annotation @Controller class).

The three-tier architecture is the architecture of the entire application, which is managed by the Spring framework. The general project structure is composed of the Service layer and the Dao layer, which are fed back to the application layer and the data access layer.

The Spring MVC framework is built around the core of DispatcherServlet, which intercepts requests and dispatches them to the appropriate processor for processing. The Spring MVC framework includes annotation driver controller, request and response information handling, view resolution, localization resolution, upload file resolution, exception handling, and form tag binding.

architecture

Spring MVC is a technical framework based on the Model 2 implementation. Spring MVC receives all requests through a DispatcherServlet and delegates the work to other components.

Spring MVC architecture

  1. The client makes an HTTP request, the Web application server receives the request, and if it matches the DispatcherServlet’s request mapping path (specified in web.xml), the Web container forwards the request to DispatcherServlet for processing.
  2. After receiving the request, the DispatcherServlet finds the Handler of the request based on the request information (including URL, HTTP method, request header, request parameters, and Cookie) and the configuration of HandlerMapping. Think of HandlerMapping as a routing controller and the Handler as the target host. It is worth noting that Spring MVC does not define a Handler interface; in fact, any Object can be a request Handler.
  3. When the DispatcherServlet obtains the Handler corresponding to the current request based on the HandlerMapping, it encapsulates the Handler through the HandlerAdapter and invokes the Handler using the unified adapter interface. HandlerAdapter is a framework level interface of Spring MVC. As its name implies, HandlerAdapter is an adapter that calls various Handler methods using a unified interface.
  4. After the processor has finished processing the business logic, it returns a ModelAndView to the DispatcherServlet, which contains the view logical name and model data information.
  5. ModelAndView contains “logical view names” instead of real view objects. DispatcherServlet uses ViewResolver to parse logical view names into real view objects.
  6. Once you have the real View object View, the DispatcherServlet uses this View object to render the View of the model data in the ModelAndView.
  7. Ultimately, the client gets a response message, which can be a plain HTML page, an XML or JSON string, or even a picture or a PDF document.

Configuration DispatcherServlet

You can configure a Servlet in web.xml by specifying the URL it handles.

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version = "3.0" > <! <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:application-context.xml</param-value> </context-param> <! (2) Start the Spring container listener, It references the context parameter at (1) to get the address of the Spring configuration file --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <! <servlet> <servlet-name>web</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <! <servlet-name>web</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>Copy the code
  1. At (1), specify the configuration file for the business-layer Spring container (for multiple configuration files, split) with the contextConfigLocation parameter.

  2. At (2), the ContextLoaderListener is a ServletLoaderListener that starts the business layer’s Spring container from the Spring configuration file specified by contextConfigLocation.

  3. At (3), a DispatcherServlet named Web is configured, which by default loads the Spring configuration file/web-INF /web-servlet.xml (-servlet.xml) to start the Spring container for the Web layer. The Web layer container will be a child of the business layer container, and the Web layer container can access the beans of the business layer container, but the business layer container cannot access the beans of the Web layer container.

  4. At (4), all HTTP requests are handled by specifying a DispatcherServlet. A web. XML can be configured with multiple DispatcherServlets, and each DispatcherServlet can be configured to handle different requests.

Configuration parameters of DispatcherServlet

You can specify configuration parameters via properties:

  1. Namespace parameter: namespace of the DispatcherServlet. Default is WEB-INF/-servlet.xml. After the parameter is explicitly configured, the path of the new configuration file is web-INF /.xml. For example, if the namespace is set to sample, the Spring configuration file is web-infple.

  2. ContextConfigLocation: If the DispatcherServlet context corresponds to the Spring configuration file has more than one, you can use this property in accordance with the specified path way, Spring resources such as the classpath: sample1. XML, the classpath: the sample2. XML.

  3. PublishContext: Defaults to true. The DispatcherServlet uses this property to decide whether to publish the WebApplicationContext to the ServletContext property list so that the caller can find the WebApplicationContext instance through the ServletContext. The corresponding attribute called DispatcherServlet# getServletContextAttributeName () returns a value.

  4. PublishEvents: Defaults to true. When the DispatcherServlet after processing a request, if you need a ServletRequestHandleEvent event to the container.

Spring Container Configuration

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd "> < context: component - scan base - package =" com. Ankeetc. Web "/ > <! - will be automatically registered with RequestMappingHandlerAdapter RequestMappingHandlerMapping the two beans, this is for SpringMVC for @ Controllers necessary to distribute the requests -- > <! - Provides data binding support, @NumberFormatAnnotation support, @dateTimeFormat support, @valid support, READ and write XML support, read and write JSON support and other functions. --> <mvc:annotation-driven /> </beans>Copy the code

Programm-based configuration

Spring 4.0 has full support for Servlet 3.0, which allows you to programmatically configure the Servlet container. In the Servlet 3.0 environment, the container will be in the classpath lookup javax.mail. Servlet. ServletContainerInitializer interface classes, if it is found that the implementation class, will use it to configure the Servlet container. Spring provides the implementation of this interface, called SpringServletContainerInitializer, this class in turn to find implementation WebApplicationInitializer classes and the configuration tasks to them. Spring also provides an implementation class AbstractAnnotationConfigDispatcherServletInitializer WebApplicationInitializer basis, Making it simply specify its Servlet mapping when registering a DispatcherServlet.

public class WebApplicationInitilalizer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { ServletRegistration.Dynamic registration = servletContext.addServlet("web", new DispatcherServlet()); registration.setLoadOnStartup(1); registration.addMapping("/"); }}Copy the code

Internal logic of the DispatcherServlet

    protected void initStrategies(ApplicationContext context) {
        initMultipartResolver(context);
        initLocaleResolver(context);
        initThemeResolver(context);
        initHandlerMappings(context);
        initHandlerAdapters(context);
        initHandlerExceptionResolvers(context);
        initRequestToViewNameTranslator(context);
        initViewResolvers(context);
        initFlashMapManager(context);
    }
Copy the code

The DispatcherServlet#initStrategies() method is executed after the WebApplicationContext has been initialized, at which point the beans in the Spring context have been initialized, This method uses reflection to find and assemble user-defined beans in the Spring container and, if not, the default component instance.

The default component

The DispatcherServlet. Properties inside the configuration file, specifies the DispatcherServlet USES the default components. If you want a non-default component, you can simply configure your custom component beans in the Spring configuration file.

# localization parser org. Springframework. Web. Servlet. LocaleResolver = org. Springframework. Web. Servlet. I18n. AcceptHeaderLocaleResolver Topic # parser org. Springframework. Web. Servlet. ThemeResolver = org. Springframework. Web. Servlet. Theme. # FixedThemeResolver processor parser org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\ Org. Springframework. Web. Servlet. MVC. The annotation. # DefaultAnnotationHandlerMapping processor adapter org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\ org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\ Org. Springframework. Web. Servlet. MVC. The annotation. # AnnotationMethodHandlerAdapter exception handler org.springframework.web.servlet.HandlerExceptionResolver=org.springframework.web.servlet.mvc.annotation.AnnotationMethod HandlerExceptionResolver,\ org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,\ Org. Springframework. Web. Servlet. MVC. Support. # DefaultHandlerExceptionResolver view name processor org.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNam ETranslator # View parser org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver org.springframework.web.servlet.FlashMapManager=org.springframework.web.servlet.support.SessionFlashMapManagerCopy the code

The DispatcherServlet assembles logic for each type of component

Annotation-driven controllers

@requestMapping Indicates mapping requests

  1. Annotate @Controller on the POJO class and use context: Component-scan to scan the class to make the POJO a Controller capable of handling HTTP requests.
  2. You can use @RequestMapping in both the controller class definition and the method definition.
  3. RequestMapping not only supports standard urls, but also Ant style and {XXX} placeholder urls.
  4. @requestMapping, Value, Method, Params, and headers indicate the mapping conditions of the request path, request method, request parameters, and packet header respectively.

Get request content

  1. You can obtain HTTP request information from @requestParam, @requestheader, and @pathVariable.
  2. You can use @cookievalue to bind a Cookie value to a method input parameter
  3. You can use the @matrixVariable annotation to bind the matrix variables in the request to the method parameters of the processor.
  4. You can bind request parameter values using a command/form object (that is, a POJO), and Spring automatically populates the object with properties in a way that matches the request parameter name with the object property name.
  5. You can use classes of the Servlet API as input arguments to processing methods, such as HttpServletRequest, HttpServletResponse, and HttpSession; If HttpServletResponse returns the corresponding, the handler returns void; inorg.springframework.web.context.requestDefines several interfaces that can proxy Servlet native API classes, such as WebRequest and NativeWebRequest.
  6. You can use Java. IO InputStream, Reader, OutputStream, and Writer as input arguments to a method.
  7. You can also use java.util.Locale and java.security.Principal as input arguments.

Using HttpMessageConverter

The HttpMessageConverter interface can convert request information to an object (type T) and bind the object (type T) to the parameters of the request method or output it as response information. DispatcherServlet RequestMethodHandlerAdapter as HandlerAdapter component has been installed by default implementation class, HttpMessageConverter used by RequestMethodHandlerAdapter, namely the request information is converted to object, or convert object to respond to messages.

HttpMessageConverter implementation class

Spring provides a number of implementation classes for HttpMessageConverter:

The implementation class

The implementation class

The default HttpMessageConverter

RequestMappingHandlerAdapter HttpMessageConverter have default assembly the following:

  • StringHttpMessageConverter
  • ByteArrayHttpMessageConverter
  • SourceHttpMessageConverter
  • AllEncompassingFormHttpMessageConverter

Assemble other types of HttpMessageConverter

If need to other types of HttpMessageConverter assembly, can be in Spring Web container context to define a RequestMappingHandlerAdapter, several HttpMessageConverter registration. If in Spring web container explicitly defines a RequestMappingHandlerAdapter, Spring MVC will use it to override the default RequestMappingHandlerAdapter.

Using HttpMessageConverter

  1. You can annotate a handler using @requestBody and @responseBody
  2. You can use HttpEntity, ResponseEntity as the input or return value of the processing method

RestTemplate is a Spring template class that you can use to invoke services on the Web server side, and it supports REST-style urls.

conclusion
  1. Spring MVC uses registered HttpMessageConvertor to handle requests and messages only when the controller handler uses @RequestBody, @ResponseBody, or HttpEntity, or ResponseEntity.
  2. When a controller handler uses @requestBody, @ResponseBody, or HttpEntity, ResponseEntity, Spring first selects the matching HttpMessageConverter based on the Accept attribute of the request header or response. If no available HttpMessageConverter is found, an error will be reported.
  3. @requestBody and @responseBody do not need to be paired.

Work with XML and JSON

Spring MVC provides several httpMessageconverters for handling request and response messages in XML and JSON formats:

  • MarshallingHttpMessageConverter: XML processing
  • Jaxb2RootElementHttpMessageConverter: dealing with XML, the underlying using JAXB
  • MappingJackson2HttpMessageConverter: processing JSON format

As long as in Spring Web container as RequestMappingHandlerAdapter corresponding HttpMessageConverter assembled, and through the request in the interaction of the Accept to specify the MIME type, Spring MVC can transparently communicate with the client through XML or JSON formats.

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
                <bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"/>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
            </list>
        </property>
    </bean>
Copy the code

Using the @ RestController

@restController already annotates @responseBody and @Controller, so you can annotate this annotation directly on the Controller instead of adding @responseBody to each @requestMapping method.

AsyncRestTemplate

Spring 4.0 provides AsyncRestTemplate for service access in an asynchronous, non-blocking manner.

public class WebApplicationInitilalizer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { ServletRegistration.Dynamic registration = servletContext.addServlet("web", new DispatcherServlet()); registration.setLoadOnStartup(1); / / here should be set to true registration. SetAsyncSupported (true); registration.addMapping("/"); } } @RestController public class AsyncController { @RequestMapping(value = "/async", method = RequestMethod.GET) public Callable<String> async() { System.out.println("hello!" ); return new Callable<String>() { @Override public String call() throws Exception { TimeUnit.SECONDS.sleep(5); return "ASYNC"; }}; } } public class Main { public static void main(String[] args) { AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate(); ListenableFuture<ResponseEntity<String>> future = asyncRestTemplate.getForEntity("http://localhost:8080/async", String.class); System.out.println("return"); future.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() { @Override public void onFailure(Throwable ex) { System.out.println("Failure"); } @Override public void onSuccess(ResponseEntity<String> result) { System.out.println("Success"); }}); }}Copy the code

Processing model data

Spring MVC provides several ways to output model data:

  1. ModelAndView: When the return value type of the processing method is ModelAndView, the method body can add model data through this object;
  2. @modelAttribute: After the annotation is annotated by the method input parameter, the object of the input parameter is placed in the data model;
  3. Map and Model: if the method into the reference for org. Framework. The UI, the Model and org. Framework. The UI. The ModelMap, Java. Util. Map, when processing method returns, Map the data will be automatically added to the Model;
  4. SessionAttributes: To temporarily store an attribute in the model in an HttpSession so that the attribute can be shared between multiple requests.

Data binding of processing methods

Spring converts and binds the information in the request to the input parameter of the request method in a certain way according to the signature of the request method. It also performs data conversion, data formatting, and data verification.

Data binding process

Data binding

Spring MVC analyzes the target signature through reflection, binding the request message to the input parameter of the processing method. The core piece of data binding is DataBinder. The Spring MVC main framework passes the ServletRequest object and the input object instance of the processing method to the DataBinder, DataBinder first calls the ConversionService component assembled in the Spring Web context for data type conversion, data formatting, and so on, populating the input object with messages from the ServletRequest. The Validator component is then called to validate the data of the input parameter object that has been bound to the request message data, resulting in the data BindingResult BindingResult object. The BindingResult contains the input parameter object that has completed the data binding, as well as the corresponding validation error object. Spring MVC extracts the BindingResult input object and the validation error object and assigns them to the corresponding input parameter of the processing method.

Data conversion

Type conversion module is located in the org. Framework. The core. The convert package, at the same time, due to historical reasons, the Spring also supports the JDK PropertyEditor.

Introduction of ConversionService

ConversionService is the core interface of the Spring type conversion architecture. It defines the following four methods:

  • Boolean canConvert(Class sourceType, Class targetType) : Determines whether one Java Class can be converted to another.
  • Boolean canConvert(TypeDescriptor sourceType, TypeDescriptor targetType) : The class to be converted will appear in the host class as a member variable. TypeDescriptor describes not only information about the class to be converted, but also context information from the host class, such as annotations on member variables, whether member variables are rendered as arrays, collections, or maps, etc. Conversion logic can use this information to make all kinds of flexible controls.
  • T convert(Object source, Class targetType) : converts an Object of the original type to an Object of the targetType.
  • Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) : When an object is converted from an object of the original type to an object of the target type, context information of the host class is often used.

The first and third interface methods are similar to the PmpertyEditor in that they do not care about the context of the type object and simply convert two types of objects, the only difference being that the two methods support conversion of any two types. The second and fourth interface methods refer to the context information of the host class in which the type object resides and use this information to perform type conversions.

Using ConversionService

Can take advantage of the org. Springframework. Context. Support. A ConversionService ConversionServiceFactoryBean defined in the context of the Spring. Spring automatically recognizes the ConversionService in the context and uses it for data transformation in situations such as Bean property configuration and Spring MVC processing method input parameter bindings. This FactoryBean creates a ConversionService that has many converters built into it to convert most Java types. In addition to converting strings to objects of various base types, it also includes converters between String, Number, Array, Collection, Map, Properties, and Object. Through ConversionServiceFactoryBean converters attribute to register a custom type converter:

    <bean class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="com.ankeetc.MyConverter"/>
            </list>
        </property>
    </bean>
Copy the code

Spring supported converters

Spring in the org. Springframework. Core. The convert. The converter package defines three types of converter interface, Implement as a converter interface can be registered as a custom converter to ConversionServiceFactoryBean. The interfaces of the three types of converters are:

  • Converter

    : Convert objects of type S to objects of type T
    ,>
  • GenericConverter: Performs type conversions based on the context information of the source object and the host class of the target object. The class a subinterface ConditionalGenericConverter, it adds a interface methods depending on the type of the source and target types in the host class context information to decide whether to type conversion.
  • ConverterFactory:

ConversionServiceFactoryBean attributes of converters can accept the Converter, ConverterFactory, GenericConverter or ConditionalGenericConverter interface implementation class, And the conversion logic of these converters is uniformly encapsulated into a ConversionService instance object (GenericConversionService). Spring will use this ConversionService instance to perform type conversion during Bean property configuration and Spring MVC request message binding.

Assemble a custom editor in Spring using @LnitBinder and WebBindingInitializer

Spring also supports JavaBeans’ PropertyEditor. Custom editors can be added to controllers using @initBinder or assembled globally using WebBindingInitializer.

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(User.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                User user = new User();
                user.setName(text);

                this.setValue(user);
            }
        });
    }
Copy the code

If you want to use it globally, you can implement the WebBindingInitializer interface and register it in the implementation class.

  1. Implements the WebBindingInitializer interface and registers a custom editor in the initBinder interface method.
  2. In the Spring context through RequestMappingHandlerAdapter assembly custom, Initializer.

The order

For objects of the same type, if a custom converter is installed in ConversionService, a custom editor is installed in WebBindinglnitializer, and a custom editor is installed in controller via @initBinder, Spring MVC then looks for the corresponding type of editor in the following order of precedence:

  1. Query custom editors assembled with @initBinder.
  2. Query custom converters assembled through ConversionService.
  3. Query custom editors assembled by WebBindingInitializer.

Data formatting

Spring converters do not format input and output information. Data of the source type (usually a string) that needs to be converted has a certain format. In different localization environments, data of the same type can be displayed in different formats. Spring introduced a new format framework, this framework is located in the org. Springframework. Format classes in the package.

The most important Formatter interface
Formatting AnnotationFormatterFactory annotation drivers

In order to make annotations and formatting attribute types, in the Spring in the Formatter package also provides a AnnotationFormatterFactory interface.

Enable annotation-driven formatting

Formatting the input/output of a property object is still essentially a type conversion. Spring builds “formatting” functionality on top of the object transformation framework. Spring in formatting module defines a FormattingConversionService implementing the ConversionService interface implementation class, the implementation class extends the GenericConversionService, Therefore, it has both type conversion function and formatting function. FormattingConversionService also has a corresponding FormattingConversionServiceFactoryBean factory class, The latter is used to construct a FormattingConversionService in the Spring context. With this factory class, you can register both custom converters and custom annotation-driven logic. Due to the automatic registration NumberFormatAnnotationFormatterFactory and FormattingConversionServiceFactoryBean, government departments JodaDateTimeFormatAnnotationFormatterFactory, so after assembling the FormattingConversionServiceFactoryBean, You can use annotation-driven formatting during Spring MVC input parameter binding and model data output. It is worth noting that the MVC: annotation – driven internal default created/label is a FormattingConversionServiceFactoryBean ConversionService instance.

Data validation

Spring has its own data validation framework and supports the JSR-303 standard validation framework. Spring’s DataBinder invokes the validation framework to perform data validation while performing data binding. In Spring MVC, data validation can be done directly in an annotation-driven manner. LocalValidatorFactoryBean both realized the Spring the Validator interface, and implement the Validator interface of JSR – 303. As long as in the Spring container defines a LocalValidatorFactoryBean, them into the need data validation in the Bean. It’s worth noting that Spring itself does not provide an implementation of JSR-303, so you must place JAR files for jSR-303 implementers (such as Hibernate Validator) in the classpath, and Spring will automatically load and assemble the implementers of JSR-303. MVC: will the annotation – driven/default assembly a LocalValidatorFactoryBean, through on the processing method of tagging @ Valid annotations, can let the Spring MVC after complete the data binding to perform data validation work.

Views and view resolvers

V. Localization

Spring provides the following four localization parsers.

  • AcceptHeaderLocaleResolver: according to the Accept HTTP message header – Language parameter to determine the geochemical types. If not explicitly define the localization parser, Spring MVC using AcceptHeaderLocaleResolver by default.
  • CookieLocaleResolver: Determines the localization type based on the specified Cookie value.
  • SessionLocaleResolver: Determines the localization type based on the value of a specific attribute in the Session.
  • LocaleChangeInterceptor: Gets the local type of this request from the request parameters.

File upload

Spring MVC provides direct support for file uploads through plug-and-play MultipartResolver. Spring uses the Jakarta Commons FileUpload technology to implement a MultipartResolver implementation class: CommonsMultipartResolver. There is no MultipartResolver installed by default in the Spring MVC context, so file uploads cannot be handled by default. If you want to use Spring’s file upload functionality, you need to configure MultipartResolver in the context.

Seven, WebSocket

Static resource processing

  1. MVC: the default servlet – handler / : After configuring MVC :default-servlet-handler/ in smart-servlet. XML, In the Spring MVC context defines a org. Springframework. Web. Servlet. Resource. DefaultServletHttpRequestHandler, it will act as an inspector role, Screen urls entering the DispatcherServlet. If a request is found to be a static resource, the request is forwarded to the default Servlet of the Web application server for processing; If it is not a request for a static resource, the DispatcherServlet continues to process it.

  2. MVC :resources/ : MVC :default-servlet-handler/ Passes the processing of static resources back to the Web application server via the Spring MVC framework. MVC: Resources/Further, the SpringMVC framework handles static resources itself and adds some useful additional functionality.

Interceptor

When a request is received, the DispatcherServlet passes the request to the HandlerMapping to find the HandlerExecutionChain object that should be requested. Before we go into HandlerMapping, it’s important to recognize the HandlerExecutionChain object.

HandlerExecutionChain

The HandlerExecutionChain is responsible for processing the request and returning the ModelAndView’s processing chain. It contains a Handler to process the request and several handlerInterceptors to intercept the request. When HandlerMapping returns the HandlerExecutionChain, the DispatcherServlet passes the request to the interceptor and handler defined in the HandlerExecutionChain. At the end of the processor chain is a Handler. The DispatcherServlet encapsulates the Handler through the Handler Adapter Adapter and calls Handler processing methods according to the unified Adapter interface. You can configure multiple interceptors in web-servlet.xml, and each interceptor can specify a matching mapping path to limit the scope of the interceptor.

X. Exception handling

Spring MVC handles exceptions through HandlerExceptionResolver, including exceptions that occur during processor mapping, data binding, and processor execution. HandlerExceptionResolver has only one interface method: Modelandview resolveException(HttpServletRequest Request HttpServletResponse Response Object Handler, Exception ex). When an exception occurs, Spring MVC calls the resolveException method and goes to the corresponding view of ModelAndView, which is fed back to the user as an exception report page.

The implementation class

HandlerExceptionResolver has four implementation classes

  1. DefaultHandlerExceptionResolver: default assembly, for converting corresponding exception error code
  2. SimpleMappingExceptionResolver: all exceptions for unified handling
  3. AnnotationMethodHandlerExceptionResolver: default register the class, allows @ ExceptionHandler annotations to specify specific exception handling
  4. ResponseStatusExceptionResolver

That’s the end of the article

Xiaobian here summarizes a springMVC mind map, want to know a little partner can have a look

Like xiaobian to share technical articles can like attention oh!

Here are some spring MVC technical materials and interview questions

Public account: Kylin bug