SpringMVC (3)_Detailed explanation of annotation controller

        Preface: This article first briefly introduces DispatcherServlet and its special beans, and then learns how to implement page controllers through annotations.

This article focuses on the following issues:

  • Briefly describe DispatcherServlet
  • Annotated Controller Details

1. Overview of DispatcherServlet

        DispatcherServlet is an implementation of the front controller design pattern (see http://super-wangj.iteye.com/blog/2388441 ), provides a centralized access point for Spring Web MVC , is responsible for the assignment of responsibilities, and works seamlessly with the Spring IoC container integrated to get all the benefits of Spring.

       DispatcherServlet is mainly used for responsibility scheduling, and itself is mainly used to control the process . The main responsibilities are as follows:

  • Through HandlerMapping, the request is mapped to the processor (returns a HandlerExecutionChain, which includes a processor and multiple HandlerInterceptor interceptors);
  • Support multiple types of handlers (handlers in HandlerExecutionChain) through HandlerAdapter;
  • Parse the logical view name to the specific view implementation through ViewResolver;
  • Rendering specific views, etc.;
  • localization analysis;
  • If an exception is encountered during execution, it will be handed over to HandlerExceptionResolver for resolution;
  • File upload parsing, if the request type is multipart, the file upload parsing will be performed through MultipartResolver.

1.1 Configuration of DispatcherServlet in web.xml

<!-- 配置 DispatcherServlet -->
<servlet>
	<servlet-name>dispatcherServlet</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:springmvc.xml</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
	<servlet-name>dispatcherServlet</servlet-name>
	<url-pattern>/</url-pattern>
</servlet-mapping>
  • load-on-startup : indicates that the servlet is initialized when the container is started;
  • url-pattern : Indicates which requests are handled by Spring Web MVC, "/" is used to define the default servlet mapping. It can also be expressed as "*.html" to intercept all requests whose extension is html.
       Note: The DispatcherServlet uses WebApplicationContext as the context by default, and the Spring default configuration file is "/WEB-INF/[servlet name]-servlet.xml".
       Initialization parameters of DispatcherServlet:
parameter describe
contextClass A class that implements the WebApplicationContext interface, which the current servlet uses to create contexts. If this parameter is not specified, XmlWebApplicationContext is used by default
contextConfigLocation A string passed to the context instance (specified by contextClass) that specifies the location of the context. This string can be split into multiple strings (using commas as delimiters) to support multiple contexts (in the case of multiple contexts, if the same bean is defined twice, the latter one takes precedence).
namespace WebApplicationContext namespace. The default value is [server-name]-servlet.

 1.2 Context

       Common configuration 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 the general configuration of Spring's integrated Web environment; it is generally used to load beans (such as DAO, Service, etc.) except for the Web layer, so as to facilitate integration with any other Web framework.

  • contextConfigLocation : Represents the configuration file used to load beans;
  • contextClass : Indicates the ApplicationContext implementation class used to load beans, the default WebApplicationContext.
       After the context is created, the context will be placed in the ServletContext. The context initialized by the ContextLoaderListener and the context initialized by the DispatcherServlet are shown in the following figure: Note: The DispatcherServlet uses the WebApplicationContext as the context by default, and the Spring default configuration file is "/WEB-INF/[ servlet name]-servlet.xml".        Initialization parameters of DispatcherServlet:        
parameter describe
contextClass A class that implements the WebApplicationContext interface, which the current servlet uses to create contexts. If this parameter is not specified, XmlWebApplicationContext is used by default
contextConfigLocation A string passed to the context instance (specified by contextClass) that specifies the location of the context. This string can be split into multiple strings (using commas as delimiters) to support multiple contexts (in the case of multiple contexts, if the same bean is defined twice, the latter one takes precedence).
namespace WebApplicationContext namespace. The default value is [server-name]-servlet.
 1.2 Context relationship          As can be seen from the figure, the context-loaded beans initialized by ContextLoaderListener are shared with the entire application, no matter what presentation layer technology is used, generally such as DAO layer and Service layer beans;
        DispatcherServlet 初始化的上下文加载的Bean 是只对Spring Web MVC 有效的Bean,如Controller、HandlerMapping、HandlerAdapter等等,该初始化上下文应该只加载Web相关组件。
        整个DispatcherServlet初始化的过程主要做了如下两件事情
  1. 初始化Spring Web MVC使用的Web 上下文,并且可能指定父容器为(ContextLoaderListener加载了根上下文);
  2. 初始化DispatcherServlet使用的策略,如HandlerMapping、HandlerAdapter等。

 1.3 DispatcherServlet中使用的特殊的Bean

          DispatcherServlet默认使用WebApplicationContext作为上下文,其上下文中特殊的Bean如下:

  • Controller:处理器/页面控制器,做的是MVC中的C 的事情,但控制逻辑转移到前端控制器了,用于对请求进行处理
  • HandlerMapping请求到处理器的映射,如果映射成功返回一个HandlerExecutionChain 对象(包含一个Handler处理器(页面控制器)对象、多个andlerInterceptor 拦截器)对象;如BeanNameUrlHandlerMapping将URL与Bean名字映射,映射成功的Bean就是此处的处理器;
  • HandlerAdapter:HandlerAdapter 将会把处理器包装为适配器,从而支持多种类型的处理器,即适配器设计模式的应用,从而很容易支持很多类型的处理器;如SimpleControllerHandlerAdapter将对实现了Controller接口的Bean进行适配,并且调用处理器的handleRequest方法进行功能处理;
  • ViewResolver:ViewResolver将把逻辑视图名解析为具体的View,通过这种策略模式,很容易更换其他视图技术;如InternalResourceViewResolver将逻辑视图名映射为jsp视图;
  • LocalResover:本地化解析,因为Spring支持国际化,因此LocalResover 解析客户端的Locale信息从而方便进行国际化;
  • ThemeResovler:主题解析,通过它来实现一个页面多套风格,即常见的类似于软件皮肤效果;
  • MultipartResolver:文件上传解析,用于支持文件上传;
  • HandlerExceptionResolver处理器异常解析,可以将异常映射到相应的统一错误界面,从而显示用户友好的界面(而不是给用户看到具体的错误信息);
  • RequestToViewNameTranslator:当处理器没有返回逻辑视图名等相关信息时,自动将请求URL 映射为逻辑视图名;
  • FlashMapManager:用于管理FlashMap的策略接口,FlashMap用于存储一个请求的输出,当进入另一个请求时作为该请求的输入,通常用于重定向场景,后边会细述。

 2. 注解式控制器

        Spring3.1之后,SpringMVC使用处理器映射RequestMappingHandlerMapping处理器适配器RequestMappingHandlerAdapter来开启支持@Controller 和 @RequestMapping 注解的处理器。

2.1 常用注解

注解 作用
@Controller 用于标识是处理器类;
@RequestMapping 请求到处理器功能方法的映射规则;
@RequestParam 请求参数到处理器功能处理方法的方法参数上的绑定;
@ModelAttribute 请求参数到命令对象的绑定;
@SessionAttributes 声明session 级别存储的属性,放置在处理器类上,通常列出模型属性(如@ModelAttribute)对应的名称,则这些属性会透明的保存到session 中;
@InitBinder 自定义数据绑定注册支持,用于将请求参数转换到命令对象属性的对应类型;
@CookieValue cookie 数据到处理器功能处理方法的方法参数上的绑定;
@RequestHeader 请求头(header)数据到处理器功能处理方法的方法参数上的绑定;
@RequestBody 请求的body体的绑定(通过HttpMessageConverter 进行类型转换;
@ResponseBody 处理器功能处理方法的返回值作为响应体(通过HttpMessageConverter进行类型转换)
@ResponseStatus 定义处理器功能处理方法/异常处理器返回的状态码和原因;
@ExceptionHandler 注解式声明异常处理器;
@PathVariable 请求URI 中的模板变量部分到处理器功能处理方法的方法参数上的绑定,从而支持RESTful 架构风格的URI;

 

2.2 配置控制器样例

2.2.1 配置web.xml

<!-- 配置Spring初始化参数(配置文件位置). -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<!-- 配置Spring监听器. -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置SpringMVC -->
<servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/spring-mvc.xml</param-value>
    </init-param>
     <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>*.action</url-pattern>
</servlet-mapping>

 2.2.2 创建 Spring MVC 配置文件

<!-- 注解扫描包(SpringMVC只关注控制器类上的注解) -->
<context:component-scan base-package="com.wj.web" />

<!-- 开启注解 -->
<mvc:annotation-driven />

<!-- 静态资源(js/image)的访问 -->
<!-- 针对SpringMVC拦截所有请求的情况下才需要配置,以防对静态资源的访问也被拦截. -->
<!-- <mvc:resources location="/js/" mapping="/js/**"/> -->

<!-- 定义视图解析器(此处针对Jsp) -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <!-- 所有URI的前缀. -->
    <property name="prefix" value="/jsp/"></property>
    <!-- 所有URI的后缀. -->
    <property name="suffix" value=".jsp"></property>
</bean>

 2.2.3 处理器定义

@Controller                     // 指明当前类是控制器
@RequestMapping("/jsp/user")    // ①处理器的通用映射前缀
public class UserController {


    @RequestMapping("/getAllUser.action") 	// ②相对于①处的映射URL进行窄化
    public String getAllUser(HttpServletRequest request){
        List<User> userList = userService.getAllUser();
        request.setAttribute("userList", userList);
        return "user/index";
    }
}

 

 

 

        DispatcherServlet 初始化的上下文加载的Bean 是只对Spring Web MVC 有效的Bean,如Controller、HandlerMapping、HandlerAdapter等等,该初始化上下文应该只加载Web相关组件。
  1. 初始化Spring Web MVC使用的Web 上下文,并且可能指定父容器为(ContextLoaderListener加载了根上下文);
  2. 初始化DispatcherServlet使用的策略,如HandlerMapping、HandlerAdapter等。

Guess you like

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