Spring MVC architecture overview

Spring MVC framework around the core DispatcherServlet expansion , DispatcherServlet is general director of Spring MVC, chief planner, which is responsible for intercepting requests and assigned to the appropriate processor. Spring MVC annotation drive frame includes an information processing controller, and in response to the request, the view resolution, a localized manner, for upload files, exception handling, and so on label binding form.

 

1. Architecture

Spring MVC is based on the technical implementation framework Model 2, Model 2 is a classic MVC (Model, View, Control) model Web application variant, this change is mainly due to the stateless protocol HTTP. Model 2 and MVC object, just as the use of a separate processor model, view and control, achieve the effect of different levels of loose layer of coupling techniques, system flexibility, maintainability and reusability. In most cases, the MVC Model 2 can be equated.

Before using the Model 2, to show all logic and business logic together, sometimes also called this application model for Model 1. The main disadvantage of Model 1 is tightly coupled, the difference reusability, high maintenance costs.

Since Spring MVC Model 2 is achieved based on the frame, so that the underlying mechanism is the MVC, Spring MVC is described by the following overall architecture of FIG.

Receiving the request returns a response, many components of Spring MVC effort with their duties, orderly manner job well. Throughout the framework, the DispatcherServlet position in the core, which is responsible for coordination and organization of the various components to complete the work request processing and returns a response. Most Web frameworks and, via a front end Spring MVC Serviet receiving all requests, and particularly for processing entrusted to other components, the front end of the DispatcherServlet Spring MVC is Servlet. Here the whole process of handling requests Spring MVC explain.

(1) The whole process starts with the client sends a HTTP request, Web application server receives this request. If the matching path map request DispatcherServlet (specified in web.xml), then the request to the Web container DispatcherServlet process.

After (2) DispatcherServlet receive this request, according to the information request (including the URL, HTTP method, the request header, the request parameters, Cookie, etc.), and a processor configured to find HandlerMapping processing request (Handler). Can be seen as a route controller, Handler will be seen as the target host. It is noteworthy that, in Spring MVC does not define a Handler interface, in fact, any Object can be a request processor.

(3) When the DispatcherServlet Handler corresponding to the current request, according to Handler HandlerMapping HandlerAdapter obtained by encapsulation, then a uniform adapter interface calls Handler. HandlerAdapter is Spring MVC framework-level interface, by definition, HandlerAdapter is an adapter, which call for a variety of methods Handler with a unified interface.

After treatment (4) of the processor to perform the business logic to return a ModelAndView DispatcherServlet, ModelAndView comprising a logical name and the model view data.

(5) ModelAndView contained a "logical view name" rather than true view object, DispatcherServlet by means ViewResolver complete logical view name-to-work a realistic view of the object.

(6) obtained when the view object's real View, DispatcherServlet on the use of the model data ModelAndView View objects in a view rendered.

(7) the client to get the final response message may be a normal HTML page, it could be an XML or JSON string, or even a picture or a PDF document, such as different forms of media.

Each step above contains a wealth of knowledge, this chapter will gradually reveal each component of the "true colors." But now please put away all the curiosity, our first step is to configure DispatcherServlet in web.xml, so Spring MVC "heart" beat up.

 

2. Configure DispatcherServIet

DispatcherServlet Spring MVC is the "soul" and "heart", which is responsible for receiving HTTP requests and coordinate the various components of the work done Spring MVC request processing. And any Servlet, users must configure DispatcherServlet in web.xml.

To understand the mechanism of the Spring MVC framework, we must answer the following three questions.

How to (1) DispatcherServlet framework to intercept certain HTTP request and handed Spring MVC framework deal?

(2) located on Spring Web container (WebApplicationContext) How to be associated with the business layer is located in the Spring container (ApplicationContext), so that the layer can invoke Web Bean Bean business layer?

(3) how to initialize the various components of Spring MVC, and assemble them into DispatcherServlet in?

1) configuration DispatcherServlet, intercept specific URL request

As you know, we can configure a Servlet in web.xml, and specify the URL of its processing by the <servlet-mapprng>. This is the traditional DispatcherServlet configuration. The Spring4.0 has full support for Servlet 3.0, therefore programmatic configuration mode can also be used. Here the first traditional way of web.xml to explain and introduce new ways of Servlet 3.0-based. Suppose we want to DispatcherServlet Spring MVC can intercept and process all requests URL to the end .html, it can be configured as follows in web.xml, as shown in the code below.

<-! - ① business layer and persistence layer Spring configuration file, the configuration file is used by the parent container Spring>
<
context-param >   < param-name > the contextConfigLocation </ param-name >   < param-value > CLASSPATH : /applicationContext.xml </ param-value > </ context-param > < listener >   < listener-class > org.springframework.web.context.ContextLoaderListener </ listener-class > </ listener >
<- ② statement! the DispatcherServlet -> < the servlet >   <servlet-name>smart</servlet-name>   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>   <load-on-startup>1</load-on-startup> </servlet> <!-- ③名为DispatcherServlet匹配的URL模式 --> <servlet-mapping>   <servlet-name>smart</servlet-name>   <url-pattern>.html</url-pattern> </servlet-mapping>

In ①, the Spring container layer designated service profile by contextConfigLocation parameter (s profiles separated by a comma). ContextLoaderListener is a ServletContextListener, that designated by the parameter Spring contextConfigLocation profile start "business layer" Spring container.

In ② Department configured DispatcherServlet called smart, which by default automatically load /WEB-INF/smart-servlet.xml(<servlet-Name>-servlet.xml) Spring configuration file, start Spring container Web layer.

In ③, the by <servlet-mappmg> designated to handle all DispatcherServlet suffix .html HTTP request, i.e., all HTTP request with .html suffix will be intercepted and processed DispatcherServlet.

We know that can be set between father and son relationship more Spring container level, in order to achieve good decoupling. Here, "web layer" Spring container as a "business layer" sub-container Spring container, namely "web layer" container can be referenced "business layer" container Bean, and "business layer" container, but not to visit "web layer "Bean container.

Need to be reminded, you can configure a plurality web.xml DispatcherServlet, through its <servlet-mapping> configuration, so that each DispatcherServlet processing different requests.

DispatcherServlet follow the principle of "contract over configuration" is, in most cases, users do not need additional configuration, can act only according to the contract.

If you really want to adjust the default rule DispatcherServlet, the Dispatcherservlet is "open-minded" in. The following are some common configuration parameters can be specified by <servlet> of <init-param>.

(1) namespace: DispatcherServlet corresponding namespace default <servlet-name> -servlet, a path configured Spring configuration file. After this property explicitly specified, the profile corresponding path WEB-INF / <namespace> .xml, not WEB-INF / <servlet-name> -servlet.xml. If the namespace is set to sample, the corresponding configuration file Spring WEB-INF / sample.xml

(2) contextConfigLocation: DispatcherServlet If the context corresponding to a plurality of profiles Sprlng, this property can be used to specify the manner Spring resource paths. The "classpath: samplel.xml, classpath: sample2.xml", DispatcherServIet using samplel.xml sample2.xml class path and both profiles initialization WebApplicationContext.

(3) publishContext: boolean attributes, the default value ture. DispatcherServlet WebApplicationContext to decide whether to publish the list of properties in the ServletContext, so that the caller can be found by means WebApplicationContext ServletContext instance, the corresponding attribute named DispatcherServlet # getServletContextAttributeName () method returns a value based on the attribute.

(4) publishEvents: boolean attributes. When DispatcherServlet finished processing a request, whether to publish a ServletRequestHandledEvent event to the vessel, the default value is true. If the container does not have any event listener, you can set this property to false, in order to improve performance.

Spring profile following code explicitly specify the web layer.

<servlet>
  <servlet-name>smart</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/webApplicationContext.xml</param-value>
    </init-param>
</servlet>

Has the full support of the previously mentioned Spring4.0 Servlet3.0, therefore, in the 3.0 environment, can also be used to programmatically configure the Servlet container. The following code can achieve the same effect as above codes.

public class SmartApplicationInitializer implements WebApplicationInitializer《
    @Override
    public void onStartup(ServletContext container){
        ServietRegistration.Dynamic registration = container.addServlet("dispatcher",new
            DispatcherServlet());
        registration.setLoadOnStartup(1);
        registration.addMapping(".html");
    }
}

Then look at the implementation of the principle of Servlet3.0. In Servlet3.0 environment, the container looks in the class path class implements javax.servlet.ServletContainerInitializer, if found to have implementation class, it will be called to configure the Servlet container. In Spring, org.springframework.web.SpringServletContainerInitializer class implements this interface, and this class will find org.springframework.web.WebApplicationInitializer class implements an interface and configure the task to implement these classes to complete. In addition, Spring provides a convenient AbstractAnnotationConfigDispatcherServletlnitializer abstract class to implement this interface, making it at the time of registration DispatcherServlet simply specify its Serviet mapping can be. In the above example, when the application deployment vessel to 3.0, when the container starts automatically find it, and use it to configure Servlet context.

2) exploring the internal logic DispatcherServIet

The last remaining question now is: Spring in the context of how Spring MVC components are assembled into DispatcherServIet in? By looking at initStrategies DispatcherServlet code () method, all the truth would come to light.

protected  void initStrategies (the ApplicationContext context) { 
    initMultipartResolver (); // ① initialization upload file parser (literal translation for the multi-part request parser) 
    initLocaleResolver (); // ② initialization localization parser 
    initThemeResolver (); // ③ initialization topic parser 
    initHandlerMappings (); // ④ processor initialization mapper 
    initHandlerAdapters (); // ⑤ initialization processor adapter 
    initHandIerExceptionResolver (); // ⑥ initialization processor exception resolver 
    initRequestToViewNameTranslator (); // ⑦ initialization request to a view name translator 
    initViewResolvers (); // ⑧ view resolver initialization 
}

initStrategies () method WebApplicationContext performed automatically after the initialization and Bean Spring context has been initialized. The working principle of this method is: Find and fitting assembly Bean Spring container user-defined explicitly by reflection, if not, the default instance of the component assembly.

Spring MVC component defines a set of default implementation class, that is to say, even if not explicitly defined in the Bean Spring container assembly, the DispatcherServlet also assembled default set of available components. In the spring-webmvc-4.x.jar package org / springframework / web has a lower profile DispatcherServlet.properties / servlet classpath, the file specified default component DispatcherServlet used.

## locale resolver 
org.springframework.web.servlet.LocaleResolver = org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver 

## theme resolver 
org.springframework.web.servlet.ThemeResolver = org.springframework.web.servlet. theme.FixedThemeResolver 

## processor map (of 2) 
org.springframework.web.servlet.HandlerMapping = org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping, \ 
    org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping 

# # processor adapter (of 3) 
org.springframework.web.servlet.HandlerAdapter = org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter, \ 
    org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter, \ 
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter 

## exception handler (total of 3)
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

有些组件最多允许存在一个实例,如 MultipartResolver、LocaleResolver 等,而另一些组件允许存在多个实例,如 HandlerMappmg、HandlerAdapter 等。同一类型的组件如果存在多个,那么它们之间的优先级顺序如何确定呢?这些组件都实现了 org.springframework.core.Ordered接口,可通过 order 属性确定优先级顺序,值越小优先级越高。

简言之,当 DispatcherServlet 初始化后,就会自动扫描上下文的 Bean,根据名称或类型匹配的机制查找自定义的组件,找不到时则使用 DispatcherServlet.properties 定义的默认组件

Guess you like

Origin www.cnblogs.com/jwen1994/p/11111769.html