Fork me on GitHub

SpringMVC学习9-Interceptor和Optional Config

Spring MVC

SpringMVC是基于MVC思想的JAVA WEB实现框架,是Spring家族的一员,它基于前置控制器来接收并分发请求,支持参考验证、请求参数封装、拦截、Restful等功能,是目前较为流行的MVC框架

本系列学习笔记包含如下的课程内容:

  • MVC思想
  • Hello案例
  • 请求和响应处理
  • 文件上传和下载处理
  • 参数验证
  • 请求拦截
  • RESTful风格
  • 日志

Interceptor(拦截器)

Spring MVC allow you to intercept web requests through interceptor.
The interceptor have to implement the HandlerInterceptor interface, which contains three methods :

  • preHandle() – Called before the handler execution, returns a boolean value, “true” : continue the handler execution chain; “false”, stop the execution chain and return it.

  • postHandle() – Called after HandlerAdapter actually invoked the handler, but before the DispatcherServlet renders the view. Can expose additional model objects to the view via the given ModelAndView.

  • afterCompletion() – Callback after completion of request processing, that is, after rendering the view. Will be called on any outcome of handler execution, thus allows for proper resource cleanup.
    Note: Will only be called if this interceptor’s preHandle method has successfully completed and returned true!

SpringMVC 可选配置(非必须)

WebMvcConfigurerAdapter

WebMvcConfig 继承 WebMvcConfigurerAdapter, Override 父类方法,来快速配置常用信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
@Configuration
@ComponentScan
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

/**
* InternalResourceViewResolver
* @return
*/
@Bean
public InternalResourceViewResolver getInternalResourceViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}

/**
* Configure a handler to delegate unhandled requests
* by forwarding to the Servlet container's "default" servlet,
* such as : /
* @param configurer
*/
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}

/**
* mapping classpath resources to public static resources
* such as : images,js,css
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**").addResourceLocations("classpath:/images/");
}
}
  • getInternalResourceViewResolver: 配置常用视图路径和后缀
  • configureDefaultServletHandling: 默认根目录
  • addResourceHandlers:将私有资源映射为公开资源

Request Method

通过 RequestMethod 来指定请求类型

1
2
3
4
5
6
7
8
9
@RequestMapping(method = RequestMethod.GET)
public Map<String, Appointment> get() {
return appointmentBook.getAppointmentsForToday();
}

@RequestMapping(path = "/{day}", method = RequestMethod.POST)
public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {
return appointmentBook.getAppointmentsForDay(day);
}

或者进一步使用具体 Mapping 类型 (仅最新版本才提供)

1
2
3
4
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping

View

form tag lib

The form tag library comes bundled in spring-webmvc.jar.
The library descriptor is called spring-form.tld.
To use the tags from this library, add the following directive to the top of your JSP page:

1
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<form:form>
<table>
<tr>
<td>First Name:</td>
<td><form:input path="firstName"/></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="lastName"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save Changes"/>
</td>
</tr>
</table>
</form:form>

Supported Method Arguments

  • Request/Response objects
  • Session object
  • Spring’s WebRequest object
  • java.util.Locale
  • java.io.Reader (access to request content)
  • java.io.Writer (access to response content)
  • java.security.Principal
  • ModelMap
  • org.springframework.validation.Errors
  • org.springframework.validation.BindingResult