一、作用
- 对请求进行预处理和后处理;
- 使用场景:
-
- 登录验证,判断用户是否登录
- 权限验证,判断用户是否有权限访问资源,如校验token
- 日志记录,记录请求操作日志(用户ip,访问时间等),以便统计请求访问量
- 处理cookie、本地化、国际化、主题等
- 性能监控,监控请求处理时长等。
二、实现
- 继承HandlerInterceptorAdapter抽象类或者实现HandlerInterceptor接口;
- 示例:
public class InterceptorDemo extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { StringBuffer requestURL = httpServletRequest.getRequestURL(); System.out.println("前置拦截器1 preHandle: 请求的uri为:"+requestURL.toString()); return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { System.out.println("拦截器1 postHandle: "); } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { System.out.println("拦截器1 afterCompletion: "); } }
四大方法:
preHandle是在请求controllor前调用,返回true才向后调用其它方法,
postHandler在调用Controller方法之后、视图渲染之前调用,
afterCompletion是在渲染视图完成之后使用,
afterConcurrentHandlingStarted方法用来处理异步请求。
三、注册
- 通过@Component 或者 @Configuration将Bean注册到spring容器中
@Configuration public class InterceptorConfig implements WebMvcConfigurer{
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册TestInterceptor拦截器 InterceptorRegistration registration = registry.addInterceptor(new InterceptorDemo()); registration.addPathPatterns("/**"); //所有路径都被拦截 registration.excludePathPatterns( //添加不拦截路径 "你的登陆路径", //登录 "/**/*.html", //html静态资源 "/**/*.js", //js静态资源 "/**/*.css", //css静态资源 "/**/*.woff", "/**/*.ttf" ); }
}