1.maven
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/>
</parent>
<groupId>org.example</groupId>
<artifactId>spring-boot-interceptor-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
@RestController
public class IndexController {
@RequestMapping("/")
public String index() {
return "this is index";
}
@RequestMapping("/login")
public String login() {
return "this is login";
}
@RequestMapping("/getDate")
public Date getDate(@RequestParam(value = "date", required = false) Date date) {
return date;
}
}
@Controller
@RequestMapping("/template")
public class TemplateController {
@RequestMapping("/index")
public String index() {
return "login_template";
}
@RequestMapping("/login")
public String login() {
return "login_template";
}
}
public class DateFormatter implements Formatter<Date> {
// 日期类型模板:如yyyy-MM-dd
private String datePattern = "yyyy-MM-dd";
// 日期格式化对象
private SimpleDateFormat dateFormat;
public DateFormatter() {
this.dateFormat = new SimpleDateFormat(datePattern);
}
/**
* 显示Formatter<T>的T类型对象
*/
@Override
public String print(Date date, Locale locale) {
return dateFormat.format(date);
}
/**
* 解析文本字符串返回一个Formatter<T>的T类型对象。
*/
@Override
public Date parse(String source, Locale locale) throws ParseException {
try {
return dateFormat.parse(source);
} catch (Exception e) {
throw new IllegalArgumentException();
}
}
}
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("- - - preHandle - - -");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("- - - postHandle - - -");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("- - - afterCompletion - - -");
}
}
2.WebMvcConfigurer配置
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
/**
* 用来注册拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
MyInterceptor interceptor = new MyInterceptor();
// 创建InterceptorRegistration对象并将自定义拦截器传入;
InterceptorRegistration interceptorRegistration = registry.addInterceptor(interceptor);
// addPathPatterns方法(指定拦截路径,往往使用 "/**")
interceptorRegistration.addPathPatterns("/**");
// excludePathPatterns方法(指定排除拦截路径,用于登录等部分开放接口)
interceptorRegistration.excludePathPatterns("/logout");
}
/**
* 资源映射
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 添加静态资源路径,然后根项目的路径进行映射
registry.addResourceHandler("/html/*")
.addResourceLocations("file:/home/zxm/html/");
registry.addResourceHandler("/js/*")
.addResourceLocations("classpath:/static/js/");
}
/**
* 一个路径自动跳转到一个页面
* 相当于使用 new ModelAndView(“login”)方法跳转
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("goToLogin")
.setViewName("login_template");
}
/**
* 设置跨域
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
// 添加映射路径,“/**”表示对所有的路径实行全局跨域访问权限的设置
CorsRegistration corsRegistration = registry.addMapping("/**");
// 允许哪些ip或域名可以跨域访问 *表示允许所以,不要写*,否则cookie就无法使用了
// (这里建议不要用 * ,*表示所以请求都允许跨域)
// springboot 2.4.0 以上时对 AllowedOrigin 设置发生了改变,不能有”*“
corsRegistration.allowedOrigins("*");
// 是否发送Cookie信息
corsRegistration.allowCredentials(true);
// 允许的请求方式
corsRegistration.allowedMethods("GET", "POST", "DELETE", "PUT");
// 表示访问请求中允许携带哪些Header信息,如:Accept、Accept-Language、Content-Language、Content-Type
corsRegistration.allowedHeaders("*");
// 暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
corsRegistration.exposedHeaders(HttpHeaders.CONTENT_DISPOSITION);
// 设置等待时间,默认1800秒
corsRegistration.maxAge(3600);
}
/**
* 通过重写 addFormatters 方法来添加数据格式化器。
* Spring MVC 接受 HTTP 请求会把参数自动绑定映射到 Controller 请求参数上。
* Spring 中没有默认配置将字符串转换为日期类型。
* 这时可以通过添加一个 DateFormatter 类来实现自动转换。
*/
@Override
public void addFormatters(FormatterRegistry registry) {
DateFormatter formatter = new DateFormatter();
registry.addFormatter(formatter);
}
}