Spring boot 拦截器配置

拦截器配置代码
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public RedisInterceptor redisInterceptor(){
        return new RedisInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 对所有访问路径,都通过MyInterceptor类型的拦截器进行拦截

        // 如果拦截器不调用service层的方法 可以直接 new RedisInterceptor()
         // 如果拦截器调用service层的方法 RedisInterceptor 必须加入Bean 不然会报错空指针
        registry.addInterceptor(redisInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/", "/login", "/index.html", "/user/login", "/css/**", "/images/**", "/js/**", "/fonts/**");
        //放行登录页,登陆操作,静态资源
    }
} 

// 拦截器执行方法

public class RedisInterceptor implements HandlerInterceptor {
  
    /**
     * 访问控制器方法前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
//        System.out.println(new Date() + "--preHandle:" + request.getRequestURL());
        return true;
    }

    /**
     * 访问控制器方法后执行
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
//        System.out.println(new Date() + "--postHandle:" + request.getRequestURL());

    }

    /**
     * postHandle方法执行完成后执行,一般用于释放资源
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
//        System.out.println(new Date() + "--afterCompletion:" + request.getRequestURL());
    }
}

你可能感兴趣的:(java,servlet,html)