Introduction to SpringMVC

Web MVC framework
1.1 Introduction to Spring MVC

1. is a model-view-controller framework designed to dispatch requests to various processors around the DispatcherServlet, with matching handler mappings, View resolution, local settings, time zone and theme resolution, and support for file uploads.
2. In Spring Web MVC, you can use any object as a command or form support object; you do not need to implement framework specific interfaces or base classes.

1.2 Spring MVC features

1. Clear role separation. The various roles - controllers, validators, command objects, form objects, model objects, DispatcherServlet, map handlers, view resolvers, etc. can all be implemented with specialized objects.
2. Both framework and program classes can use the powerful JavaBeans configuration directly, these configurations contain simple context references, such as from controllers to business objects and validators.
3. Applicability, non-intrusiveness, flexibility, define any controller method signature you need. May be used such as (@RequestParam, @RequestHeader, @PathVariable).
4. The reusable business code does not need to be written repeatedly, and is replaced by existing business objects such as command objects or form objects.
5. Customizable binding and validation, such as localized data and value binding, instead of just manual parsing and conversion of business objects with string form objects.
6. Customizable map processors and view resolvers. Strategies for map processors and view resolvers range from simple URL-based configuration to complex specialized parsing strategies, and are more flexible than other frameworks.
7. Flexible model transfer, basic key/value map model, easy to integrate with any view technology.
8. Customizable localization, time zone and theme parsing. Supports JSPs or JSPs without Spring tag library, supports JSTL, and has built-in support for Velocity.
9. Provides a simple and powerful JSP tag library called Spring tag library, supports functions such as data binding and themes, and provides maximum flexibility in tagging code by customizing the tag library.
10. The JSP form tag library has been introduced since Spring 2.0, making it easier to write forms in JSP.
11. The life cycle scope of Beans is limited to the current HTTP request or HTTP Session, which is not provided by Spring MVC and is limited by the WebApplicationContext container used.

1.3 Request Processing Flow

Spring's Web MVC framework, like many other Web MVC frameworks, is request-driven, designed around a central servlet that sends requests to controllers, and provides other features that facilitate Web application development. But Spring's DispatcherServlet doesn't just do this. It is fully integrated with the Spring IoC container, thus allowing you to use every other feature of Spring.

 

1. Request Processing Flowchart


 
 
DispatcherServlet is an actual servlet (it inherits from the HttpServlet base class), so it can be declared in a web application. You need to use URL mapping to map requests to be handled by DispatcherServlet. The following is a standard Java EE servlet configuration in a Servlet 3.0+ environment:

 

public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {
        ServletRegistration.Dynamic registration = container.addServlet("example", new DispatcherServlet());
        registration.setLoadOnStartup(1);
        registration.addMapping("/example/*");
    }

}
 All requests starting with /example in this configuration will be handled by the DispatcherServlet instance named Example. WebApplicationInitializer is an interface provided by Spring MVC that ensures your code-based configuration is detected and automatically used to initialize any Servlet 3 container. The abstract base class implementation of the AbstractAnnotationConfigDispatcherServletInitializer interface makes it easier to register the DispatcherServlet by simply specifying its servlet mapping and listing the configuration classes.

 

 

It can also be declared in web.xml, the following is a standard Java EE Servlet configuration.

 

 

<web-app>
    <servlet>
        <servlet-name>example</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>example</servlet-name>
        <url-pattern>/example/*</url-pattern>
    </servlet-mapping>

</web-app>
 

 

 

In the Web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext.

 

2. Typical context hierarchy in Spring Web MVC

 

 

 
 When initializing the DispatcherServlet, Spring MVC will look for a file named [servlet-name]-servlet.xml in the WEB-INF directory of the web application and create the bean defined there, overriding the one defined in the global scope with the same name Definition of any bean.

as the following DispatcherServlet configuration

 

 

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

 

 

使用上述Servlet配置,您需要在应用程序中有一个名为/WEB-INF/golfing-servlet.xml的文件; 该文件将包含您所有的Spring Web MVC特定组件(bean)。 您可以通过Servlet初始化参数更改此配置文件的指定位置。

 

3.Spring Web MVC中的单根上下文




 
 

可以通过设置一个空的ContextConfigLocation servlet init参数进行配置,如下所示:

 

 

<web-app>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/root-context.xml</param-value>
    </context-param>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>
 

 

WebApplicationContext是普通ApplicationContext的扩展,它具有Web应用程序所需的一些额外功能。 它与普通的ApplicationContext不同之处在于它能够解析主题,并且它知道它与哪个Servlet相关联(通过连接到ServletContext)。 WebApplicationContext绑定在ServletContext中,并且通过在RequestContextUtils类上的静态方法,您可以随时查找WebApplicationContext。

 

我们可以通过基于Java的配置实现

 

public class GolfingWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        // GolfingAppConfig defines beans that would be in root-context.xml
        return new Class[] { GolfingAppConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        // GolfingWebConfig defines beans that would be in golfing-servlet.xml
        return new Class[] { GolfingWebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/golfing/*" };
    }

}
 

 

3.WebApplicationContext中的特殊Bean类型

HandlerMapping 将请求映射到一个处理器列表,它包含前置处理器和后置处理器(处理拦截器),其细节由HandlerMapping实现而异。 最流行的实现支持注释控制器,但其他实现也存在。
HandlerAdapter 主要是用来屏蔽DispatcherServlet 的技术细节,它帮助DispatcherServlet 调用映射到请求的处理程序,而不管实际调用哪个处理程序,如调用带注释的控制器需要解析各种注释。
HandlerExceptionResolver 将异常映射到视图,也允许更复杂的异常处理代码。
ViewResolver 将基于逻辑字符串的视图名称解析为实际的View类型。
LocaleResolver & LocaleContextResolver 解决客户端正在使用的区域设置以及可能的时区,以便能够提供国际化的视图。
ThemeResolver 解决您的Web应用程序可以使用的主题,例如,提供个性化的布局
MultipartResolver 解析多部分请求,以支持从HTML表单处理文件上传。
FlashMapManager 存储并检索“输入”和“输出”FlashMap,它可以用于将属性从一个请求传递到另一个请求,通常是通过重定向。

 

4.默认DispatcherServlet配置

 

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
 Once you configure a special bean (such as InternalResourceViewResolver) in the WebApplicationContext, the default implementation list for that special bean type is overridden. For example, if InternalResourceViewResolver is configured, the default list of ViewResolver implementations is ignored.

 

 

5. DispatcherServlet processing sequence

在您设置了DispatcherServlet并且针对该特定DispatcherServlet启动了一个请求后,DispatcherServlet将按如下所示开始处理请求:

• Search and bind the WebApplicationContext in the request as a property that can be used by controllers and other elements in the process. By default it will be bound under the DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE key. ● The locale resolver is bound to the request to enable elements in the process to resolve the locale used when processing the request (rendering views, preparing data, etc.). If you don't need locale parsing, you don't need it. • A theme resolver is bound to a request that allows elements such as views to determine which theme to use. It can be ignored if the theme is not used. ● If a multipart file parser is specified, the request is checked for multipart; if multipart is found, the request is wrapped in a MultipartHttpServletRequest for further processing by other elements in the process. ● Search for an appropriate handler, and if one is found, prepare the model or render the view by executing the execution chain associated with the handler (preprocessor, postprocessor, and controller). ● Render the view if a model is returned. If no model is returned (perhaps due to a preprocessor or postprocessor intercepting the request, such as failing to pass for security reasons), no view will be rendered because the request may have already been fulfilled. A handler declared in the WebApplicationContext exception resolver fetches exceptions during processing of the request. Using these exception parsers allows you to define custom behavior for resolving exceptions. Spring DispatcherServlet also supports returning the last modified date specified by the Servlet API. The process of determining the last modification date of a particular request is simple: DispatcherServlet looks up the appropriate handler mapping and tests whether the handler found implements the LastModified interface. If it is, the value of the long getLastModified(request) method of the LastModified interface will be returned to the client. DispatcherServlet initialization parameters
contextClass 实现WebApplicationContext的类,它实例化了这个Servlet使用的上下文。 默认情况下,使用XmlWebApplicationContext。
contextConfigLocation 传递给上下文实例(由contextClass指定)以指示可以找到上下文的字符串,该字符串可能包含多个字符串(使用逗号作为分隔符)来支持多个上下文。在具有两次定义的bean的多个上下文位置的情况下,最后定义的优先级最高。
namespace WebApplicationContext的命名空间。 默认为[servlet-name] -servlet。
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326337057&siteId=291194637