码迷,mamicode.com
首页 > 编程语言 > 详细

Spring Boot 编写一个拦截器

时间:2020-06-21 00:33:03      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:执行   public   view   conf   err   创建   全局   str   return   

创建一个类并使其实现接口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 编写一个拦截器

标签:执行   public   view   conf   err   创建   全局   str   return   

原文地址:https://www.cnblogs.com/esrevinud/p/13170990.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!