首页 > 其他分享 >SpringBoot - 自定义拦截器HandlerInterceptor

SpringBoot - 自定义拦截器HandlerInterceptor

时间:2022-12-27 17:23:17浏览次数:38  
标签:Exception 拦截器 SpringBoot 自定义 Override public HandlerInterceptor

1.实现HandlerInterceptor接口

/**
 * 自定义拦截器
 */
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("====在该方法执行之前执行====");
        // 返回true才会继续执行,返回false则取消当前请求
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("执行完方法之后进执行(Controller方法调用之后),但是此时还没进行视图渲染");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("整个请求都处理完咯,DispatcherServlet也渲染了对应的视图咯,此时我可 以做一些清理的工作了");
    }
}

2.在配置类中注册自定义拦截器

@Configurationpublic class AppConfig {
    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new MyInterceptor())
                        .addPathPatterns("/**") //要拦截的请求
                        .excludePathPatterns("/","/index","/css/**","/js/**");//不拦截的请求
            }
        };
    }
}

 

标签:Exception,拦截器,SpringBoot,自定义,Override,public,HandlerInterceptor
From: https://www.cnblogs.com/ErenYeager/p/17008549.html

相关文章