- 创建一个类实现HandlerInterceptor接口
- 添加到spring容器中
简单例子:
public class MyInterceptor implements HandlerInterceptor { /** * 请求处理之前执行 * @param request * @param response * @param handler * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("=======请求处理之前执行========="); return false; } /** * 请求进行处理之后执行 * @param request * @param response * @param handler * @param modelAndView * @throws Exception */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("===========请求进行处理之后执行=========="); } /** * 当前对应的interceptor的perHandle方法的返回值为true时,postHandle执行完成并渲染页面后执行 * @param request * @param response * @param handler * @param ex * @throws Exception */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("==========当前对应的interceptor的perHandle方法的返回值为true时,postHandle执行完成并渲染页面后执行==========="); } }
配置适配器
@Configuration public class MyMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()) .addPathPatterns("/signIn") //需要拦截的路径 .excludePathPatterns("/login","/login.html"); //不需要拦截的路径 } }
拦截器用途很广,比如可以用来进行接口权限控制,登陆,日志记录等等。