Spring Boot 编写一个拦截器
Posted esrevinud
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot 编写一个拦截器相关的知识,希望对你有一定的参考价值。
创建一个类并使其实现接口HandlerInterceptor
接口提供了一个请求的三个周期的拦截方法
在controller之前,返回true则放行,false反之,handler包含处理请求的controller类以及其方法
boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
在controller接受请求之后,contorller渲染视图之前,如果发生异常就不执行了,可对ModelAndView操作
void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
在controller处理全部完成之后,ex参数包含处理期间发生的异常,但仅为未被全局捕获的异常
void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
public class TheInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion");
}
}
编写完成后需要将其注册进处理栈中才会生效, 创建WebMvcConfigurer
的实现类
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor())
// 需要拦截的路径,默认全部拦截
.addPathPatterns("/test1")
// 需要排除的路径
.excludePathPatterns("/test2");
}
}
以上是关于Spring Boot 编写一个拦截器的主要内容,如果未能解决你的问题,请参考以下文章