10 knowledge points for you to understand spring MVC container



With spring boot gradually covering our project, we have basically forgotten the classic combination of servlet + spring MVC, which is very familiar web.xml to configure. In this article, we want to put aside spring boot and go back to the past to see how servlet integrates with spring MVC and how to initialize spring container.

  • Spring MVC overview
  • Annotation driven controller
  • Data binding of processing methods
  • An attempt was made to communicate with the view parser
  • localization
  • File upload
  • WebSocket
  • Static resource processing
  • Interceptor
  • exception handling

1、 Overview of spring MVC

MVC: model + view + controller

Three tier architecture

Three tier architecture: presentation tier + application tier + data tier (presentation tier + application tier + data access tier)

The relationship between MVC and three tier architecture

The relationship between MVC and three-tier architecture,MVC has only three layers of presentation.

M is actually a data model and an object containing data. In spring MVC, there is a special class called model, which is used for data interaction and value transfer with V.
V refers to the view interface, including JSP, FreeMarker, velocity, thymeleaf, tile, etc.
C is the controller (spring MVC annotation @ controller class).

The three-tier architecture is the architecture of the whole application, which is managed by the spring framework. In general, the project structure is composed of service layer and Dao layer. The two feedback layers are in the application layer and data access layer.

Spring MVC framework is developed around the core of dispatcher servlet, which is responsible for intercepting requests and dispatching them to the corresponding processor for processing. Spring MVC framework includes annotation driven controller, information processing of request and response, view parsing, localization parsing, upload file parsing, exception handling and form label binding.


Spring MVC is a technical framework based on model 2. Spring MVC receives all the requests through a dispatcher servlet and delegates the specific work to other components for processing.

10 knowledge points for you to understand spring MVC container

Spring MVC architecture

  1. The client sends an HTTP request, and the web application server receives the request. If it matches the request mapping path of the dispatcher servlet (in the web.xml The web container forwards the request to the dispatcher servlet for processing.
  2. After receiving the request, the dispatcher servlet will find the handler to process the request according to the request information (including URL, HTTP method, request header, request parameter, cookie, etc.) and the configuration of handlermapping. Handlermapping can be regarded as routing controller and handler as target host. It is worth noting that there is no handler interface defined in spring MVC. In fact, any object can be a request processor.
  3. When the dispatcher servlet gets the handler corresponding to the current request according to handlermapping, it encapsulates the handler through handleradapter, and then calls the handler with a unified adapter interface. Handleradapter is the framework level interface of spring MVC. As the name suggests, handleradapter is an adapter, which calls various handler methods with a unified interface.
  4. After processing the business logic, the processor will send back a modelandview to the dispatcher servlet. Modelandview contains the view logical name and model data information.
  5. Modelandview contains “logical view name” instead of real view object. Dispatcherserservlet uses viewresolver to resolve logical view name to real view object.
  6. After getting the real view object view, the dispatcher servlet uses this view object to render the model data in modelandview.
  7. Finally, the response message received by the client may be an ordinary HTML page, or an XML or JSON string, or even an image or a PDF document.

“2020 latest Java foundation intensive lecture video tutorial and learning route! 》

Configure dispatcherservlet

Can be in web.xml Configure a servlet in and specify the URL it handles.

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">

    <! -- (1) load spring configuration file from classpath -- >

    <! -- (2) is responsible for starting the listener of the spring container, which will refer to the context parameter at (1) to get the address of the spring configuration file -- >

    <! -- (3) configure dispatcherserservlet -- >
    <! -- (4) specifies the URL path for processing -- >

Copy code
  1. At (1), specify the configuration file of the business layer spring container through the contextconfiglocation parameter (multiple configuration files use the,Split).
  2. At (2), contextloaderlistener is a servlet loaderlistener, which starts the spring container of the business layer through the spring configuration file specified by contextconfiglocation.
  3. At (3), a dispatcher servlet named web is configured, which loads / WEB-INF / web by default- servlet.xml (- servlet.xml )To start the spring container of the web layer. The web layer container will be the sub container of the business layer container. The web layer container can access the bean of the business layer container, but the business layer container cannot access the bean of the web layer container.
  4. At (4), by specifying the dispatcher servlet/*All HTTP requests. One web.xml Multiple dispatcherservlets can be configured to handle different requests.

Configuration parameters of dispatcherservlet

Configuration parameters can be specified through the following properties:

  1. Namespace parameter: the namespace corresponding to the dispatcher servlet. The default is web-inf/- servlet.xml . After the parameter is explicitly configured, the path corresponding to the new configuration file is WEB-INF /. XML. For example, if the namespace is set to sample, the corresponding spring configuration file is web- INFmple.xml .
  2. Contextconfiglocation: if there are multiple spring configuration files corresponding to the dispatcherserservlet context, you can use this attribute to specify the spring resource path, such as classpath:sample1.xml , classpath:sample2.xml .
  3. Publishcontext: true by default. According to this attribute, dispatcherservlet decides whether to publish webapplicationcontext to the attribute list of ServletContext, so that callers can find webapplicationcontext instances through ServletContext. The corresponding attribute name is the return value of dispatcherservlet # getservletcontextattributename().
  4. Publishevents: true by default. When the dispatcher servlet has finished processing a request, whether it is necessary to issue a servlet requesthandleevent event to the container.

Spring container configuration

<beans xmlns="http://www.springframework.org/schema/beans"

    <context:component-scan base-package="com.ankeetc.web"/>
    <! -- two bean, requestmappinghandlermapping and requestmappinghandleradapter, will be registered automatically, which is necessary for spring MVC to distribute requests for @ controllers -- >
    <! -- and provides data binding support, @ numberformata annotation support, @ datetimeformat support, @ valid support, reading and writing XML support and reading and writing JSON support. -->
    <mvc:annotation-driven />

Copy code

Programming based configuration

Spring 4.0 has fully supported servlet 3.0, and you can configure the servlet container programmatically. In the servlet 3.0 environment, the container looks for the implementation in the classpath javax.servlet.ServletContainerInitializer If the implementation class is found, it will be used to configure the servlet container. Spring provides the implementation of this interface, which is called springservletcontainerinitializer. This class in turn looks up the classes that implement webapplicationinitializer and gives them the task of configuration. Spring also provides a basic implementation class of webapplicationinitializer, abstractannotationconfigdispatcherservletinitializer, which enables it to simply specify its servlet mapping when registering dispatcherservlet.

public class WebApplicationInitilalizer implements WebApplicationInitializer {
    public void onStartup(ServletContext servletContext) throws ServletException {
        ServletRegistration.Dynamic registration = servletContext.addServlet("web", new DispatcherServlet());
Copy code

The internal logic of dispatcherservlet

protected void initStrategies(ApplicationContext context) {
Copy code

The dispatcherservlet # initstrategies() method will be executed after the webapplicationcontext is initialized. At this time, the bean in the spring context has been initialized. This method finds and assembles the user-defined bean in the spring container through reflection, and assembles the default component instance if it cannot be found.

Default component

stay DispatcherServlet.properties In the configuration file, the default component used by the dispatcher servlet is specified. If users want to use non default components, they just need to configure the custom component bean in the spring configuration file.

#Localization parser

#Topic parser

#Processor parser

#Processor adapter

#Exception handler

#View name processor

#View parser

Copy code

10 knowledge points for you to understand spring MVC container

The logic of dispatcherservlet assembling all kinds of components

2、 Annotation driven controller

@Requestmapping mapping requests

  1. Mark @ controller on the POJO class, and then context:component-scan After scanning this class, POJO can become a controller that can handle HTTP requests.
  2. The corresponding processing method of @ requestmapping mapping can be used in the class definition and method definition of the controller.
  3. @Requestmapping supports not only standard URLs, but also ant style URLs and {XXX} placeholders.
  4. @Requestmapping and value, method, params and headers represent the mapping conditions of request path, request method, request parameter and message header respectively.

Get request content

  1. HTTP request information can be obtained through @ requestparam, @ requestheader, @ pathvariable.
  2. You can use @ cookie value to bind a cookie value to the 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 use the command / form object (that is, a POJO) to bind the request parameter value. Spring will automatically fill in the attributes for the object according to the matching between the request parameter name and the object attribute name.
  5. You can use the classes of servlet API as the input parameters of processing methods, such as HttpServletRequest, httpservletresponse, and httpsession. If you use httpservletresponse to return the corresponding data, the processing method will return and set to voidorg.springframework.web.context.requestSeveral interfaces of proxy servlet native API classes are defined, such as webrequest and native webrequest.
  6. have access to java.io InputStream, reader, OutputStream, and writer in are used as input parameters of the method.
  7. It can also be used java.util.Locale 、 java.security.Principal As a reference.

Using httpmessage converter

The httpmessage converter interface can convert the request information into an object (type T) and bind the object (type T) to the parameters of the request method or output it as the response information. Dispatcherserservlet has installed requestmethodhandleradapter as the implementation class of handleradapter component by default. Httpmessage converter is used by requestmethodhandleradapter to convert request information into object or object into response information.

Implementation class of httpmessage converter

Spring provides many implementation classes for httpmessage converter

10 knowledge points for you to understand spring MVC container

Implementation class

10 knowledge points for you to understand spring MVC container

Implementation class

10 knowledge points for you to understand spring MVC container

Default httpmessage converter

Requestmappinghandleradapter has the following httpmessage converter installed by default:

  • StringHttpMessageConverter
  • ByteArrayHttpMessageConverter
  • SourceHttpMessageConverter
  • AllEncompassingFormHttpMessageConverter

Assemble other types of httpmessage converter

If you need to assemble other types of httpmessage converters, you can define a requestmapping handler adapter in the web container context of spring to register several httpmessage converters. If a requestmappinghandleradapter is explicitly defined in the spring web container, spring MVC will use itcoverThe default requestmappinghandleradapter.

Using httpmessage converter

  1. You can use @ requestbody, @ ResponseBody to annotate processing methods
  2. Httpentity and responseentity can be used as input parameters or return values of processing methods

Resttemplate is the template class of spring, which can be used to call web server services. It supports rest style URL.

  1. When the controller processing method uses @ requestbody, @ ResponseBody or httpentity, responseentity, spring MVC will use the registered httpmessage converter to process the request and corresponding messages.
  2. When the controller processing method uses @ requestbody, @ ResponseBody or httpentity, responseentity, spring first selects the matching httpmessage converter according to the request header or the response’s accept attribute, and then obtains the matching httpmessage converter according to the parameter type or generic type filtering. If no available httpmessage converter is found, an error will be reported.
  3. @Requestbody, @ ResponseBody do not need to appear in pairs.

Dealing with XML and JSON

Spring MVC provides several httpmessage converters to handle requests in XML and JSON formats and respond to messages

  • Marshalling httpmessage converter: Handling XML
  • Jaxb2root element httpmessage converter: processes XML, and uses JAXB as the underlying layer
  • Mapping Jackson 2httpmessage converter: Handling JSON format

As long as the corresponding httpmessage converter is assembled for the requestmappinghandleradapter in the spring web container, and the MIME type is specified by the request’s accept in the interaction, spring MVC can be the processing method of the server segment and communicate with the client transparently through XML or JSON format.

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

Using @ restcontroller

@The restcontroller has annotated @ ResponseBody and @ controller. You can annotate the annotation directly on the controller instead of adding @ ResponseBody to each @ requestmapping method.


Spring 4.0 provides asyncresttemplate for asynchronous and non blocking service access.

public class WebApplicationInitilalizer implements WebApplicationInitializer {
    public void onStartup(ServletContext servletContext) throws ServletException {
        ServletRegistration.Dynamic registration = servletContext.addServlet("web", new DispatcherServlet());
        //Set to true here

public class AsyncController {

    @RequestMapping(value = "/async", method = RequestMethod.GET)
    public Callable<String> async() {
        return new Callable<String>() {
            public String call() throws Exception {
                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);

        future.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
            public void onFailure(Throwable ex) {

            public void onSuccess(ResponseEntity<String> result) {
Copy code

Processing model data

Spring MVC provides a variety of 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 marked on the method input parameter, the object of the input parameter will be put into the data model;
  3. Map and model: if the method input parameter is org.framework.ui .Model、 org.framework.ui .ModelMap、 java.util.Map When the processing method returns, the data in the map will be automatically added to the model;
  4. @Session attributes: temporarily store an attribute in the model to httpsession, so that multiple requests can share this attribute.

3、 Data binding of processing methods

Spring will transform and bind the information in the request to the input parameter of the request method in a certain way according to the different signature of the request method. It will also perform data conversion, data formatting and data verification.

Data binding process

10 knowledge points for you to understand spring MVC container

Data binding

Spring MVC analyzes the target signature through reflection and binds the request message to the input parameter of the processing method. The core component of data binding is data binder. The main framework of spring MVC passes the instance of the input parameter object of the ServletRequest object and processing method to the databinder. Firstly, the databinder calls the conversionservice component assembled in the spring Web context for data type conversion and data format, and fills the message in the ServletRequest into the input parameter object, Then the Validator component is invoked to verify the data legality of the object that has bound the request message data, and finally to generate the data binding result BindingResult object. Bindingresult contains the input parameter object that has completed data binding, and also contains the corresponding verification error object. Spring MVC extracts the input parameter object and validation error object from bindingresult, and assigns them to the corresponding input parameter of the processing method.

data conversion

The type conversion module is located in the org.framework.core At the same time, due to historical reasons, spring also supports JDK’s propertyeditor.

Introduction to conversionservice

Conversionservice is the core interface of spring type conversion system. It defines the following four methods:

  • Boolean canconvert (class sourcetype, class TargetType): judge whether one Java class can be converted to another Java class.
  • Boolean canconvert (TypeDescriptor sourcetype, TypeDescriptor TargetType): the class to be converted will appear in the host class as a member variable. TypeDescriptor not only describes the information of the class to be transformed, but also describes the context information of the host class, such as the annotation on the member variable, whether the member variable is presented in the form of array, collection or map, etc. Type conversion logic can make use of this information to make a variety of flexible control.
  • T convert (object source, class TargetType): converts an object of the original type to an object of the target type.
  • Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType):
    When converting an object from the original type to the target type, the context information of the host class is often used.

The first and the third interface methods are similar to the pmpertyeditor. They don’t care about the context information of the type object, and only simply complete the conversion of the two type objects. The only difference is that the two methods support the conversion of any two types. The second and fourth interface methods refer to the context information of the host class of the type object and use this information for type conversion.

Using conversionservice

Available org.springframework.context . support.ConversionServiceFactoryBean Define a conversionservice in the context of spring. Spring will automatically identify the conversionservice in the context, and use it for data conversion in bean property configuration and spring MVC processing method input parameter binding. The factorybean creates conversionservice with many built-in converters, which can complete the conversion of most Java types. In addition to converting string objects to various basic types of objects, it also includes converters between string, number, array, collection, map, properties and object. You can register a custom type converter through the converters property of conversionservicefactorybean

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

Spring supported converters

Spring in org.springframework.core . convert.converter There are three types of converter interfaces defined in the package. Any converter interface can be registered in conversionservicefactorybean as a custom converter. The three types of converter interfaces are as follows:

  • Converter < s, t >: converts an object of type s to an object of type T
  • Genericconverter: performs type conversion according to the context information of the host class of the source class object and the target class object. This class also has a sub interface, conditionalgenericconverter, which adds an interface method to decide whether to cast according to the context information of the host class of the source type and the target type.
  • ConverterFactory:

The converters property of convertionservicefactorybean can accept the implementation classes of converter, converterfactory, genericconverter or conditionalgenericconverter interface, and encapsulate the conversion logic of these converters into a convertionservice instance object (genericconvertionservice). Spring will use this conversionservice instance to complete type conversion when configuring bean properties and binding spring MVC request messages.

Using @ lnitbinder and webbindinginitializer to assemble custom editor in spring

Spring also supports JavaBeans’ property editor. You can use @ initbinder to add a custom editor in the controller, or you can use webbindinginitializer to assemble a global editor.

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

Copy code

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

  1. The webbindinginitializer interface is implemented, and the user-defined editor is registered in the initbinder interface method.
  2. Assemble the custom initializer in the context of spring through the requestmappinghandleradapter.


For an object of the same type, if a user-defined converter is installed in conversionservice, a user-defined editor is installed through webbindingoptimizer, and a user-defined editor is installed through @ initbinder in the controller, then spring MVC will find the editor of the corresponding type in the following order of priority:

  1. Query the custom editor assembled by @ initbinder.
  2. Query custom converters assembled through conversionservice.
  3. Query the custom editor assembled through the webbindinginitializer.

Formatting Data

Spring’s converter does not provide input and output information formatting. Generally, the source type data (usually string) that needs to be converted has a certain format. In different localization environments, the same type of data will show different display formats accordingly. Spring introduces a new formatting framework, which is located in org.springframework.format Class package.

The most important formatter interface
Annotation driven formatting annotation formatterfactory

In order to associate annotations with formatted attribute types, spring also provides an annotation formatterfactory interface in the same package as formatter.

Enable annotation driven formatting

Formatting the input / output of attribute objects still belongs to the category of “type conversion” in essence. Spring is based on the object transformation framework to implant the “format” function. Spring defines a formattingconversionservice implementation class in the format module to implement the conversionservice interface. The implementation class extends the genericconversionservice, so it has both type conversion function and format function.
Formattingconversionservice also has a correspondingFormattingConversionServiceFactoryBeanFactory class, which is used to construct a formattingconversionservice in the context of spring. Through this factory class, you can register both custom converters and custom annotation driven logic. Since the formattingconversionservicefactorybean will automatically register the numberformatanotationformatterfactory and jodadatetimeformatanotationformatterfactory internally, after the formattingconversionservicefactorybean is assembled, the annotation driven formatting function can be used in spring MVC input parameter binding and model data output.
It’s worth noting that, mvc:annotation-driven/ The conversionservice instance created by default inside the tag is a formattingconversionservicefactorybean.

data verification

Spring has its own independent data verification framework, and supports jsr-303 standard verification framework. When data binding, spring’s databinder can call the verification framework to complete data verification. In spring MVC, data verification can be directly driven by annotations.
Localvalidatorfactorybean implements both spring’s validator interface and jsr-303’s validator interface. As long as a local validator factorybean is defined in the spring container, it can be injected into the bean that needs data validation. It is worth noting that spring itself does not provide the implementation of jsr-303, so the jar file of the implementer of jsr-303 (such as hibernate validator) must be put under the classpath, and spring will automatically load and assemble the implementer of jsr-303.
mvc:annotation-driven/ A local validator factorybean will be assembled by default. Spring MVC can perform data verification after data binding by marking the @ valid annotation on the input parameter of the processing method.

4、 Views and view parsers

5、 Localization

Spring provides the following four localized parsers.

  • Acceptheaderlocalereresolver: determines the localization type according to the accept language parameter of HTTP header. If no localization parser is explicitly defined, spring MVC uses acceptheaderlocaleresolver by default.
  • Cookie localereresolver: determines the localization type based on the specified cookie value.
  • Session localereresolver: determines the localization type based on the specific property values in the session.
  • Localchangeinterceptor: get the localization type corresponding to this request from the request parameters.

6、 File upload

Spring MVC provides direct support for file upload through plug and play multipartresolver. Spring implements a multipartresolver implementation class: commonsmultipartresolver by using Jakarta Commons fileUpload technology.
In the context of spring MVC, multipartresolver is not installed by default, so file upload cannot be processed by default. If you want to use spring’s file upload function, you need to configure multipartresolver in the context first.

7、 Websocket

8、 Static resource processing

  1. mvc:default-servlet-handler/ : in smart- servlet.xml Medium configuration mvc:default-servlet-handler/ In the spring MVC context, a org.springframework.web . servlet.resource.DefaultServletHttpRequestHandler It will act as an inspector to screen the URLs entering the dispatcher servlet. If a static resource request is found, it will be transferred to the default servlet of the web application server for processing; if it is not a static resource request, it will be processed by the dispatcher servlet.
  2. mvc:resources/ : mvc:default-servlet-handler/ The processing of static resources is returned to the web application server through the spring MVC framework. and mvc:resources/ Furthermore, the spring MVC framework handles static resources by itself and adds some useful additional functions.

9、 Interceptor

When a request is received, the dispatcher servlet gives the request to the handler mapping to find out the handler execution chain object corresponding to the request. Before explaining handlermapping, it is necessary to recognize the handlerexecutionchain object.

10 knowledge points for you to understand spring MVC container


The handlerexecutionchain is responsible for processing the request and returning the processing execution chain of modelandview. It includes a handler to process the request and several handlerinterceptors to intercept the request. When handlermapping returns handlerexecutionchain, dispatcherservlet hands the request to the interceptor and processor defined in handlerexecutionchain for processing.
At the end of the processor chain is a handler. The dispatcher servlet encapsulates the handler through the handler adapter adapter and calls the handler processing method according to the unified adapter interface. Can be inweb-servlet.xmlEach interceptor can specify a matching mapping path to limit the scope of the interceptor.

10、 Exception handling

Spring MVC handles program exceptions through handlerexceptionresolver, including processor mapping, data binding, and exceptions during processor execution. Handlerexceptionresolver has only one interface method: modelandview resolveexception (HttpServletRequest httpservletresponse object handler, exception Ex). When an exception occurs, spring MVC will call the resolveexception method and go to the view corresponding to modelandview to feed back to the user as an exception report page.

Implementation class

Handlerexceptionresolver has four implementation classes

  1. Defaulthandlerexceptionresolver: this class is assembled by default and converts the corresponding exception to an error code
  2. Simplemapping exception resolver: handle all exceptions uniformly
  3. Annotationmethodhandlerexceptionresolver: this class is registered by default, allowing the @ exceptionhandler annotation to handle specific exceptions
  4. ResponseStatusExceptionResolver

That’s the end of the article

Xiaobian here summarizes a mind map of spring MVC, which can be seen by those who want to know

10 knowledge points for you to understand spring MVC container