DispatcherServlet in Spring MVC _ dynamic node Java school arrangement,

Source: Internet
Author: User
Tags i18n

DispatcherServlet in Spring MVC _ dynamic node Java school arrangement,

Roles of DispatcherServlet

DispatcherServlet is the implementation of the front-end controller design pattern. It provides Spring Web MVC centralized access points and is responsible for assigning responsibilities. It is also seamlessly integrated with Spring IoC containers to achieve all the benefits of Spring. For details, see Figure 2-1 in Chapter 2.

DispatcherServlet is mainly used for Job Scheduling and is mainly used to control the process. Its main responsibilities are as follows:

1. File Upload parsing. If the request type is multipart, the file upload will be parsed through MultipartResolver;
2. map requests to the processor through HandlerMapping (A HandlerExecutionChain is returned, which includes one processor and multiple HandlerInterceptor interceptors );
3. HandlerAdapter supports multiple types of processors (processors in HandlerExecutionChain );
4. Use ViewResolver to parse the logical view name to a specific view;
5. Local parsing;
6. rendering specific views;
7. If an exception occurs during execution, HandlerExceptionResolver will be handed over for parsing.

From the above we can see that DispatcherServlet is mainly responsible for process control (and every key point in the process is easily Scalable ).

Configuration of DispatcherServlet in web. xml

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

Load-on-startup: Initializes the Servlet when the container is started;

Url-pattern:Indicates which requests are sent to Spring Web MVC for processing. "/" is used to define the default servlet ing. You can also use "*. html" to intercept all requests with the extension html.

The DispatcherServlet uses WebApplicationContext as the context by default, and the Spring default configuration file is "/WEB-INF/[servlet name]-servlet. xml ".

DispatcherServlet can also configure its own initialization parameters to overwrite the Default Configuration:

Parameters

Description

ContextClass

Class that implements the WebApplicationContext interface. The current servlet uses it to create the context. If this parameter is not specified, XmlWebApplicationContext is used by default.

ContextConfigLocation

String passed to the context instance (specified by contextClass) to specify the context location. This string can be divided into multiple strings (using commas as the separator) to support multiple contexts (in the case of multiple contexts, if the same bean is defined twice, followed by a priority ).

Namespace

WebApplicationContext namespace. The default value is [server-name]-servlet.

Therefore, we can add initialization parameters

   <servlet>    <servlet-name>chapter2</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <load-on-startup>1</load-on-startup>    <init-param>      <param-name>contextConfigLocation</param-name>      <param-value>classpath:spring-servlet-config.xml</param-value>    </init-param>  </servlet>

If you use the above configuration, the Spring Web MVC Framework loads "classpath: spring-servlet-config.xml" to initialize the context rather than "/WEB-INF/[servlet name]-servlet. xml ".

Context

General configurations for integrated Web environment:

<context-param>   <param-name>contextConfigLocation</param-name>   <param-value>     classpath:spring-common-config.xml,     classpath:spring-budget-config.xml   </param-value></context-param><listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>

The above configuration is a general configuration for Spring to integrate the Web environment. It is generally used to load beans (such as DAO and Service) except the Web layer for integration with any other Web framework.

ContextConfigLocation: indicates the configuration file used to load the Bean;

ContextClass: The ApplicationContext implementation class used to load beans. The default value is WebApplicationContext.

After creation, the context will be placed in ServletContext:

servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,this.context);

Context of the ContextLoaderListener initialization context and DispatcherServlet initialization, 3-1

Figure 3-1

We can see that:
The context-loaded Bean initialized by ContextLoaderListener is shared with the entire application. No matter what presentation layer technology is used, such as the DAO layer and Service layer Bean;
The Bean loaded by the context initialized by DispatcherServlet is only valid for Spring Web MVC, such as Controller, HandlerMapping, and HandlerAdapter. The initialization context should only load Web-related components.

DispatcherServlet initialization sequence

The inheritance architecture is as follows:

1. HttpServletBean inherits HttpServletTherefore, when the Web Container starts, it will call its init method. The main function of this initialization method is
: Set the Servlet initialization parameter (init-param) to this component (for example, contextAttribute, contextClass, namespace, and contextConfigLocation). Use BeanWrapper to simplify the value setting process and facilitate subsequent use;
: It is provided to the subclass to initialize the extension point, initServletBean (). This method is overwritten by FrameworkServlet.

Public abstract class HttpServletBean extends HttpServlet implements EnvironmentAware {@ Override public final void init () throws ServletException {// some code is omitted // 1. The following code sets Servlet initialization parameters to this component // such as contextAttribute, contextClass, namespace, and contextConfigLocation; try {PropertyValues pvs = new ServletConfigPropertyValues (getServletConfig (), this. requiredProperties); BeanWrapper bw = PropertyAccessorFactory. f OrBeanPropertyAccess (this); ResourceLoader resourceLoader = new ServletContextResourceLoader (getServletContext (); bw. registerCustomEditor (Resource. class, new ResourceEditor (resourceLoader, this. environment); initBeanWrapper (bw); bw. setPropertyValues (pvs, true);} catch (BeansException ex ){//............ Omit other code} // 2. provide extension points for subclass initialization. This method overwrites initServletBean () by FrameworkServlet; if (logger. isDebugEnabled () {logger. debug ("Servlet" + getServletName () + "'configured successfully ");}}//............ Omit other code}

 FrameworkServlet inherits HttpServletBean, Web context initialization through initServletBean (). This method mainly covers two things:

Initialize the web context;

Provides extension points for subclass initialization;

Public abstract class FrameworkServlet extends HttpServletBean {@ Override protected final void initServletBean () throws ServletException {// omit some code try {// 1. initialize the Web context this. webApplicationContext = initWebApplicationContext (); // 2. Provided to the extension point initFrameworkServlet () ;}// omitted part of the code} protected WebApplicationContext initWebApplicationContext () {// ROOT context (loaded by ContextLoaderListener) WebApplicationContext RootContext = WebApplicationContextUtils. getWebApplicationContext (getServletContext (); WebApplicationContext wac = null; if (this. webApplicationContext! = Null) {// 1. Create the Servlet injection context wac = this. webApplicationContext; if (wac instanceof ConfigurableWebApplicationContext) {ableablewebapplicationcontext cwac = (ConfigurableWebApplicationContext) wac; if (! Cwac. isActive () {if (cwac. getParent () = null) {cwac. setParent (rootContext);} configureAndRefreshWebApplicationContext (cwac); }}if (wac = null) {// 2. Search for the bound context wac = findWebApplicationContext ();} if (wac = null) {// 3. if no corresponding context is found, specify the parent as ContextLoaderListener wac = createWebApplicationContext (rootContext);} if (! This. refreshEventReceived) {// 4. Refresh the context (perform initialization) onRefresh (wac);} if (this. publishContext) {// Publish the context as a servlet context attribute. string attrName = getServletContextAttributeName (); getServletContext (). setAttribute (attrName, wac); // omitting some code} return wac ;}

As can be seen from the initWebApplicationContext () method, basically if the ContextLoaderListener loads the context, it will act as the root context (the parent container of DispatcherServlet ).

Finally, the onRefresh () method is called to execute some container initialization. This method is implemented by sub-classes for extension.

DispatcherServlet inherits FrameworkServletAnd implements the onRefresh () method to provide some front-end controller-related configurations:

Public class DispatcherServlet extends FrameworkServlet {// onRefresh () method that implements the subclass. This method is delegated as the initStrategies () method. @ Override protected void onRefresh (ApplicationContext context) {initStrategies (context);} // initialize the policy used by the default Spring Web MVC framework (such as HandlerMapping) protected void initStrategies (ApplicationContext context) {initMultipartResolver (context); initLocaleResolver (context); initThemeResolver (context); initHandlerMappings (context); initHandlerAdapters (context); Combine (context ); initViewResolvers (context); initFlashMapManager (context );}}

From the code above, we can see that at the startup of DispatcherServlet, We will configure the Web layer Bean we need, such as HandlerMapping and HandlerAdapter. If we do not configure the Bean, we will also provide the default configuration.

From the code above, we can see that the entire DispatcherServlet initialization process and what has been done, specifically to do the following two things:

1. initialize the Web context used by Spring Web MVC, and specify the parent container as (ContextLoaderListener loads the root context );
2. initialize the policies used by DispatcherServlet, such as HandlerMapping and HandlerAdapter.

Log Analysis during server startup (ContextLoaderListener is added here to start the ROOT context container ):

Information: Initializing Spring root WebApplicationContext // start the ROOT context by ContextLoaderListener 2012-03-12 13:33:55 [main] INFO org. springframework. web. context. contextLoader-Root WebApplicationContext: initialization started2012-03-12 13:33:55 [main] INFO org. springframework. web. context. support. xmlWebApplicationContext-Refreshing Root WebApplicationContext: startup date [Mon Mar 12 13:33:55 CST 2012]; roo T of context hierarchy2012-03-12 13:33:55 [main] DEBUG org. springframework. beans. factory. xml. defaultBeanDefinitionDocumentReader-Loading bean definitions2012-03-12 13:33:55 [main] DEBUG org. springframework. beans. factory. xml. xmlBeanDefinitionReader-Loaded 0 bean definitions from location pattern [/WEB-INF/ContextLoaderListener. xml] 2012-03-12 13:33:55 [main] DEBUG org. springframework. web. context. Support. xmlWebApplicationContext-Bean factory for Root WebApplicationContext: org. springframework. beans. factory. support. defaultListableBeanFactory @ 1c05ffd: defining beans []; root of factory hierarchy2012-03-12 13:33:55 [main] DEBUG org. springframework. web. context. support. xmlWebApplicationContext-Bean factory for Root WebApplicationContext: 13:33:55 [main] DEBUG org. springframework. Web. context. contextLoader-Published root WebApplicationContext as ServletContext attribute with name [org. springframework. web. context. webApplicationContext. ROOT] // bind the ROOT context to the ServletContext2012-03-12 13:33:55 [main] INFO org. springframework. web. context. contextLoader-Root WebApplicationContext: initialization completed in 438 MS // The ROOT context is started up 13:33:55 [main] DEBUG org. springframewo Rk. web. servlet. dispatcherServlet-Initializing servlet 'chapter2' information: Initializing Spring FrameworkServlet 'chapter2' // start Initializing the Web context of FrameworkServlet 13:33:55 [main] INFO org. springframework. web. servlet. dispatcherServlet-FrameworkServlet 'chapter2': initialization started2012-03-12 13:33:55 [main] DEBUG org. springframework. web. servlet. dispatcherServlet-Servlet with name 'chapter2' w Ill try to create custom WebApplicationContext context of class 'org. springframework. web. context. support. xmlWebApplicationContext ', using parent context [Root WebApplicationContext: startup date [Mon Mar 12 13:33:55 CST 2012]; root of context hierarchy] // use Root WebApplicationContext as the parent container. 2012-03-12 13:33:55 [main] INFO org. springframework. web. context. support. xmlWebApplicationContext-Refreshing WebApplicationContext for namespace 'chapter2-servlet ': startup date [Mon Mar 12 13:33:55 CST 2012]; parent: Root WebApplicationContext2012-03-12 13:33:55 [main] INFO org. springframework. beans. factory. xml. xmlBeanDefinitionReader-Loading XML bean definitions from ServletContext resource [/ WEB-INF/chapter2-servlet.xml] 13:33:55 [main] DEBUG org. springframework. beans. factory. xml. defaultBeanDefinitionDocumentReader-Loading bean definitions2012-03-12 13:33:55 [main] DEBUG org. springframework. beans. factory. xml. beanDefinitionParserDelegate-Neither XML 'id' nor 'name' specified-using generated bean name [org. springframework. web. servlet. handler. beanNameUrlHandlerMapping #0]/ /Our configured HandlerMapping2012-03-12 13:33:55 [main] DEBUG org. springframework. beans. factory. xml. beanDefinitionParserDelegate-Neither XML 'id' nor 'name' specified-using generated bean name [org. springframework. web. servlet. mvc. simpleControllerHandlerAdapter #0] // HandlerAdapter2012-03-12 we configured 13:33:55 [main] DEBUG org. springframework. beans. factory. xml. beanDefinitionParserDelegate-Neither XML 'id' no R 'name' specified-using generated bean name [org. springframework. web. servlet. view. internalResourceViewResolver #0] // Our configured ViewResolver2012-03-12 13:33:55 [main] DEBUG org. springframework. beans. factory. xml. beanDefinitionParserDelegate-No XML 'id' specified-using '/hello' as bean name and [] as aliases // Our processor (HelloWorldController) 2012-03-12 13:33:55 [main] DEBUG org. springframework. beans. fac Invalid. xml. xmlBeanDefinitionReader-Loaded 4 bean definitions from location pattern [/WEB-INF/chapter2-servlet.xml] 2012-03-12 13:33:55 [main] DEBUG org. springframework. web. context. support. xmlWebApplicationContext-Bean factory for WebApplicationContext for namespace 'chapter2-servlet ': org. springframework. beans. factory. support. defaultListableBeanFactory @ 1372656: defining beans [org. springframework. Web. servlet. handler. beanNameUrlHandlerMapping #0, org. springframework. web. servlet. mvc. simpleControllerHandlerAdapter #0, org. springframework. web. servlet. view. internalResourceViewResolver #0,/hello]; parent: org. springframework. beans. factory. support. defaultListableBeanFactory @ 1c05ffd // The Bean registered to this container has been initialized. 2012-03-12 13:33:56 [main] DEBUG org. springframework. web. servlet. dispatcherServlet-Unable to locate MultipartResolver with name 'multipartresolver ': no multipart request handling provided 2012-03-12 13:33:56 [main] DEBUG org. springframework. beans. factory. support. defaultListableBeanFactory-Creating instance of bean 'org. springframework. web. servlet. i18n. acceptHeaderLocaleResolver '// The default LocaleResolver registration 2012-03-12 13:33:56 [main] DEBUG org. springframework. beans. factory. support. defaultListableBeanFa Ctory-Creating instance of bean 'org. springframework. web. servlet. theme. fixedThemeResolver '// The default ThemeResolver registration 2012-03-12 13:33:56 [main] DEBUG org. springframework. beans. factory. support. defaultListableBeanFactory-Returning cached instance of singleton bean 'org. springframework. web. servlet. handler. beanNameUrlHandlerMapping # 0' // we found that the HandlerMapping we defined no longer uses the default HandlerMapping. 2012-03-12 13:33:56 [main] DEBUG org. springframework. beans. factory. support. defaultListableBeanFactory-Returning cached instance of singleton bean 'org. springframework. web. servlet. mvc. simpleControllerHandlerAdapter # 0' // we found that the HandlerAdapter we defined no longer uses the default HandlerAdapter. 2012-03-12 13:33:56 [main] DEBUG org. springframework. beans. factory. support. defaultListableBeanFactory-Creating instance of bean 'org. springframework. web. servlet. mvc. annotation. annotationMethodHandlerExceptionResolver '// exception handler ExceptionResolver2012-03-12 13:33:56 [main] DEBUG org. springframework. beans. factory. support. defaultListableBeanFactory-Creating instance of bean 'org. springframework. web. servlet. mvc. annotation. annotationMethodHandlerExceptionResolver '13:33:56 [main] DEBUG org. springframework. beans. factory. support. defaultListableBeanFactory-Returning cached instance of singleton bean 'org. springframework. web. servlet. view. internalResourceViewResolver # 0' 13:33:56 [main] DEBUG org. springframework. web. servlet. dispatcherServlet-Published WebApplicationContext of servlet 'chapter2' as ServletContext attribute with name [org. springframework. web. servlet. frameworkServlet. CONTEXT. chapter2] // bind the Web context initialized by FrameworkServlet to ServletContext2012-03-12 13:33:56 [main] INFO org. springframework. web. servlet. dispatcherServlet-FrameworkServlet 'chapter2': initialization completed in 297 ms2012-03-12 13:33:56 [main] DEBUG org. springframework. web. servlet. dispatcherServlet-Servlet 'chapter2' configured successfully // the complete process ends.

As shown in the preceding log, DispatcherServlet performs some default configurations. Next, let's take a look at the default configuration.

Default DispatcherServlet Configuration

The default configuration of DispatcherServlet is in DispatcherServlet. properties (the DispatcherServlet class is in the same package), and is the Default policy used when no configuration is specified in the Spring configuration file:

 org.springframework.web.servlet.LocaleResolver=org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver org.springframework.web.servlet.ThemeResolver=org.springframework.web.servlet.theme.FixedThemeResolver org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\  org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\  org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\  org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter org.springframework.web.servlet.HandlerExceptionResolver=org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver,\  org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,\  org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver org.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver org.springframework.web.servlet.FlashMapManager=org.springframework.web.servlet.support.SessionFlashMapManager  

From the above configuration, we can see that the DispatcherServlet will automatically register these special beans at startup, so we do not need to register them. If we register these beans, they will not be registered by default.

Therefore, for example, the BeanNameUrlHandlerMapping and SimpleControllerHandlerAdapter in Chapter 2 do not need to be registered, and DispatcherServlet registers the two beans by default.

We can see from DispatcherServlet. properties that there are many special beans. Next we will look at what special beans Spring Web MVC mainly has.

Special Bean used in DispatcherServlet

DispatcherServlet uses WebApplicationContext as the context by default, so let's take a look at the special beans in this context:

1. Controller: The processor/Page controller does C in MVC, but the control logic is transferred to the front-end controller to process the request;

2. HandlerMapping: Request to the processor ing. If the ing is successful, a HandlerExecutionChain object (including one Handler processor (page Controller) object and multiple HandlerInterceptor interceptors) object will be returned; for example, BeanNameUrlHandlerMapping maps the URL to the Bean name. The Bean mapped successfully is the processor here;

3. HandlerAdapter: HandlerAdapter will package the processor into an adapter to support a variety of types of processors, that is, the application of the adapter design mode, so that it can easily support many types of processors; for example, SimpleControllerHandlerAdapter will adapt the Bean implementing the Controller Interface, and remove the handleRequest method of the processor for functional processing;

4. ViewResolver: ViewResolver resolves the logical View name to a specific View. This policy mode makes it easy to change other View technologies. For example, InternalResourceViewResolver maps the logical View name to a jsp View;

5. LocalResover: Localized resolution. Because Spring supports internationalization, LocalResover parses the Locale information of the client to facilitate internationalization;

6. ThemeResovler:Theme parsing, through which multiple styles of a page are implemented, that is, common skin effects similar to software;

7. MultipartResolver: File Upload parsing, used to support file upload;

8. HandlerExceptionResolver: Processor exception parsing. You can map exceptions to the corresponding unified error interface to display a user-friendly interface (instead of showing users specific error information );

9. RequestToViewNameTranslator: When the processor does not return information such as the logical view name, the request URL is automatically mapped to the logical view name;

10. FlashMapManager: A policy interface used to manage FlashMap. FlashMap is used to store the output of a request. When another request is entered, it is used as the input of the request. It is usually used for redirect scenarios and will be described later.

Now we know about DispatcherServlet. Next we need to break down the special Bean mentioned above. Let's start with the Controller first.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.