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"); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)