拦截器的使用及配置
拦截器(Interceptor) 类似于Servlet中的过滤器(Filter) , 它主要用于拦截用户请求并作相应的处理。例如通过拦截器可以进行权限验证、记录请求信息的日志、判断用户是否登录等。
编写拦截器
public class LoginInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("1:preHandle方法,在控制器方法执行之前执行。。。。");
//返回true 放⾏ 返回false阻⽌
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("3:postHandle方法,在控制器方法执行之后执行。。。。");
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("5:afterCompletion方法,在所有工作完成之后执行,关闭资源等操作。。。。。");
}
}
配置拦截器
//Spring Boot 1.X版本中的写法
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**")//定义拦截路径
.excludePathPatterns("/file/**"); //排除拦截路径
}
}
//Spring Boot 2.X版本中的写法
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**")//定义拦截路径
.excludePathPatterns("/file/**"); //排除拦截路径
}
}