SpringMVC Digging Road 2 - DispatcherServler + Controller
###Role of DispatcherServlet
DispatcherServlet is the implementation of the front-end controller design pattern, which provides the centralized access point of SpringWebMVC, is responsible for the assignment of responsibilities, and can be seamlessly integrated with SpringIoC container, so as to obtain all the capabilities of Spring.
DispatcherServlet is mainly used for duty scheduling, and it is mainly used for process control. Its main duties are as follows:
1:File upload resolution, if the request type is multipart, file upload resolution will be performed through MultipartResolver
2:Map the request to the processor through HandlerMapping (return a HandlerExecutionChain, which includes a processor and multiple HandlerInterceptor interceptors)
3:Many types of processors (processors in HandlerExecutionChain) are supported through HandlerAdapter
4:Resolve the logical view name to the concrete view implementation through ViewResolver
7:If an exception is encountered during execution, it will be handed over to HandlerExceptionResolver for resolution
###DispatcherServler Configure
DispatcherServlet can also configure its own initialization parameters, that is, <init-param> can be configured in servlet configuration.
###The relationship of context
The general context configuration of SpringWeb project is as follows:
org.springframework.web.context.ContextLoaderListener
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
contextConfigLocation : Represents the configuration file path used to load Bean;
contextClass : Represents the ApplicationContext implementation class used to load Bean, the default WebApplicationContext```
###Initialization order of DispatcherServlet
1:HttpServletBean inherits HttpServlet, so its init method will be called when the Web container starts
2:FrameworkServlet inherits HttpServletBean, initialize the Web context through initServletBean ()
3:DispatcherServlet inherits FrameworkServlet, and implemented onRefresh () method to provide some front-end controller related configurations
>In the DispatcherServlet of SpringMVC framework, around line 470:
* This implementation calls {@link #initStrategies}.
protected void onRefresh(ApplicationContext context) {
* Initialize the strategy objects that this servlet uses.
* <p>May be overridden in subclasses in order to initialize further strategy objects.
protected void initStrategies(ApplicationContext context) {
initMultipartResolver(context);
initLocaleResolver(context);
initThemeResolver(context);
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initRequestToViewNameTranslator(context);
initViewResolvers(context);
initFlashMapManager(context);
**The whole DispatcherServler initialization process mainly does two things:**
> * Initialize the Web context used by SpringMVC, and possibly specify the parent container (ContextLoaderListener loads the root context)
> * Initialize the policy used by DispatcherServlet, such as HandlerMapping、HandlerAdapter
###DispatcherServler Default Configure:
The default configuration of DispatcherServlet is in DispatcherServlet.properties (under the same package as DispatcherServlet class), and it is the default policy used when no configuration is specified in Spring configuration file.
It can be seen from the configuration that the DispatcherServlet will automatically register these special Bean when it starts, so we don't need to register. If we register, the default will not be registered.
###The special Bean which in DispatcherServlet
DispatcherServlet uses WebApplicationContext as the context by default, and there are some Bean in this context as follows:
Processor/page controller, doing C in MVC, but the control logic is transferred to the front-end controller for processing requests;
The mapping from processor is requested, and if the mapping is successful, a HandlerExecutionChain object (including a Handler processor (page processor) object and multiple HandlerInterceptor interceptors) is returned; For example, BeanNameUrlHandlerMapping maps URL and Bean name, and the Bean that is successfully mapped is the processor here;
HandlerAdapter will package the processor as an adapter, thus supporting many types of processors, that is, the application of adapter design pattern, thus easily supporting many types of processors; For example, SimpleControllerHandlerAdapter will adapt the Bean that implements the Controller interface and call the handleRequest method of the processor for functional processing;
The ViewResolver will resolve the logical View name into a concrete view, for example, the InternalResourceViewResoulver will map the logical view name into a jsp view;
Localized parsing, because Spring supports internationalization, the LocaleResolver parses the Locale information of the client to facilitate internationalization;
Theme analysis, through which multiple styles of a page can be realized, that is, the common effect similar to software skin;
File upload analysis, used to support file upload;
####HandlerExceptionResolver
Processor exception resolution, which can map exceptions to the corresponding agreed error interface, so as to display a user-friendly interface (instead of showing users specific error information);
####RequestToViewNameTranslator
Automatically mapping the request URL to the logical view name when the processor does not return the relevant information such as the logical view name;
It is used to manage the policy interface of FlashMap, which is used to store the output of one request, and when entering another request, it is used as the input of the request, which is usually used to redirect the scene.
###Controller brief introduction
Controller, which is the part C in MVC, is mainly responsible for the function processing part
1、Collect, validate and bind request parameters to command objects
2、Give the command object to the business object, and the business object will process and return the model data
3、Return ModelAndView(Model model part is the model data returned by the business object, and the view part is the logical view name)
###DisaptcherServler + Controller
DispatcherServlet is responsible for entrusting the request to the Controller for processing, and then selecting a specific view for rendering according to the logical view name returned by the Controller (and passing in the model data)
**The complete C (including logic control and function processing) in MVC consists of (DispatcherServlet+Controller)
Before Spring2.5, we all defined our processor class by implementing the Controller interface or its implementation class (which is no longer recommended).
Spring2.5 introduces annotated processor support, and defines processor classes through @Controller and @RequestMapping annotations. And provides a powerful set of annotations:
Spring3.0 introduces Restful architecture style support (supported by @PathVariable annotation and some other features), and introduces more annotation support
Spring3.1 use new HandlerMapping and HandlerAdapter to support @Controller and @RequestMapping annotation processors, Use the combination of processor mapping RequestMappingHandlerMapping and processor adapter RequestMappingHandlerAdapter to replace the processor mapping defaultannotationhandlermapping and processor adapter AnnotationMethodHandlerAdapter started in Spring2.5.
###Annotation implementation Controller
The configure of HandlerMapping and HandlerAdapter
> * Previous versions of Spring3.1:
DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter
> * The version starting with Spring3.1:
RequestMappingHandlerMapping and RequestMappingHandlerAdapter
Code structure reference:
https://blog.csdn.net/qq_33811662/article/details/80658813
Modify the content of spring-mvc.xml as follows:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<context:component-scan base-package="mvc1"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
Modify the contents of HelloController as follows:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
public class HelloController {
@RequestMapping("/hello")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("进入后台控制器");
ModelAndView mv = new ModelAndView();
mv.addObject("content", "SpringMVC 初体验");
mv.setViewName("/WEB-INF/jsp/hello.jsp");
Run the Server, enter the URL: