springboot配置拦截器

如下代码即可完成

@Configuration
public class LoginConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(new AdminInterceptor());
        interceptorRegistration.addPathPatterns("/**");// /**标识拦截所有
        interceptorRegistration.excludePathPatterns(//添加不需要拦截的资源
                "/jquery-easyui-1.7.0/**",//标识拦截jquery-easyui-1.7.0文件夹及其子文件夹下的资源
                "/js/**"
        );
    }
}

 

public class AdminInterceptor implements HandlerInterceptor {
    private static Logger logger = Logger.getRootLogger();
    /**
     * 在请求处理之前进行调用(Controller方法调用之前)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        logger.info("请求被拦截路径:"+request.getServletPath());
        String path = request.getServletPath();
        if (path.matches("buhefalujing")) {
            logger.info("请求被拦截路径开始处理:"+path);
            //处理过程...
            logger.info("请求被拦截路径处理完毕:"+path);
            //判断是否放行
        } else {
            logger.info("请求被拦截路径合法通过:"+path);
            return true;
        }
        return true;
    }

    /**
     * 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
         //System.out.println("执行了TestInterceptor的postHandle方法");
    }

    /**
     * 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //System.out.println("执行了TestInterceptor的afterCompletion方法");
    }
}

 

你可能感兴趣的:(springboot,拦截器,springboot)