前言:必要的说明
-
拦截器特性的变化
Spring4时代,拦截器的定义是:动态拦截Action调用的对象的组件
Spring5时代,拦截器不光能够拦截动态资源,也会拦截静态资源
-
配置方法的变化
在SpringMVC中,需要的是在mvc.xml中配置拦截器
在SpringBoot中,需要的是在WebMvcConfigurer中配置拦截器
-
声明拦截器的新方式
在Java7的时候,通过继承HandlerInteceptorAdapter来声明一个拦截器
在Java8中,由于可以直接空实现,所以可以直接实现HandlerInteceptor接口,而不用再在去继承HandlerInteceptorAdapter了,也就是说原先的适配器其实没有必要再去使用了
以下是拦截器的配置使用,所有配置均按照最新的来配置
- 拦截器的声明
public class CheckLoginInteceptor implements HandlerInteceptor{
@Override
public void preHandle(HttpServletRequest req,HttpServletResponse resp,Object handler){
//由于Spring5的新特性会拦截静动态资源,所以
if(handler instanceof HandlerMethod){
//判断session中是否有对象
//UserContext为自设工具类,主要是从session中取对象用的
User user = UserContext.getCurrentUser();
if(!Optional.ofNullable(user).isPresent()){
resp.sendRedirect("/login.html");
return false;
}
}
//其他情况放行
return true;
}
}
- 拦截器的配置
@SpringBootApplication
@Import(CoreConfig.class)
@PropertySource("classpath:application.properties")
public class WebSiteApplication implements WebMvcConfigurer{
//此处对拦截器进行注册,这里需要拦截器的一个对象
//以及配置拦截目录,以及例外目录
public void addInteceptors(InteceptorRegistry registry){
registry.addInteceptor(new CheckLoginInteceptor())
.addPathPatterns("/**")
.excludePathPatterns("/login.html","/login");
}
public static void main(String args[]){
SpringBootApplication.run(WebSiteApplication.class,args);
}
}