1.自定义拦截器
SpringMVC的拦截器执行流程
- 自定义拦截器有三个方法preHandle postHandle afterCompletion
- preHandle相当于Servlet的Filter过滤器
- preHandle+postHandle相当于@AspectJ的环绕通知Around
- 一个请求的流程运行到afterComletion时,请求体本身已经执行完毕,一般很少在afterCompletion进行一些处理,不过可以把日志记录单独放在afterCompletion里面
- 都执行的话,preHandle顺序执行,然后目标方法,postHandler逆序执行,最后再afterCompletion逆序执行
HandlerInterceptor和HandlerInterceptorAdapter区别
- HandlerInterceptor是接口,必须自己重写三个方法:perHandle、postHandle、afterCompletion
- HandlerInterceptorAdapter是实现类,直接继承后可以按需重写
HandlerInterceptor接口
HandlerInterceptorAdapter实现类
- 这个实现类是对HandlerInterceptor的封装,开发人员可以按需重写。
- 当然个人觉得大差不差,过滤可以用Filter,环绕可以用@AspectJ,如果需要在目标方法结束之后进行日志记录的话还是得重写afterCompletion
代码示例
@Slf4j
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
long start = System.currentTimeMillis();
request.setAttribute("startTime", start);
return true;//直接放行
// return HandlerInterceptor.super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
long start = (long) request.getAttribute("startTime");
long end = System.currentTimeMillis();
request.setAttribute("handleTime",end-start);
// HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info(
String.format("本次请求%s的%s接口耗时%s毫秒",
request.getRequestURL(),
request.getMethod(),
(long)request.getAttribute("handleTime")));
// HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
2.WebMvcConfigurer接口配置MVC拦截器
在springboot之前需要写xml来配置拦截器,现在可以直接通过WebMvcConfigurer 接口来配置,当然有其他的配置接口,但不推荐,WebMvcConfigurerAdapter、WebMvcConfigurationSupport
详情操作参考:
为什么用WebMvcConfigurer
→MVC配置api
//@Component效果跟@Configuration一样
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor ()).addPathPatterns("/login/web")
.excludePathPatterns("/login/no");
}
}
拦截的接口如下:
@PostMapping("/web")
public DtoRes webTest(HttpServletRequest request , HttpServletResponse response ,@RequestBody DtoReq dtoReq) throws IOException {
System.out.println(dtoReq);
return null;
}
控制台输出:
|