SpringBoot使用拦截器


SpringBoot使用拦截器

拦截器Interceptor

Spring MVC的拦截器(Interceptor)和Filter不同,但是也可以实现对请求进行预处理,后处理。先介绍它的使用,只需要两步:

1、继承HandlerInterceptor类实现拦截器

/**
 * PC端登录拦截
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入LoginInterceptor拦截器---------------------------------------");
        HttpSession session = request.getSession();
        User userInfo = (User) session.getAttribute("userInfo");
        if (userInfo == null){
            // 重定向 登录页面     ?请求url
            response.sendRedirect("/layuiAdminbl/login.html?url="+request.getRequestURL().toString());
            return false;
        }
        //放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // System.out.println("后置方法执行..");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // System.out.println("完成方法执行..");
    }
}

2、实现WebMvcConfigurer接口注册自定义拦截器

实现拦截器后还需要将拦截器注册到spring容器中,可以通过implements WebMvcConfigurer,覆盖其addInterceptors(InterceptorRegistry registry)方法。记得把Bean注册到Spring容器中,可以选择@Component 或者 @Configuration。

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Resource
    private LoginInterceptor loginInterceptor;
    /**
     * 注册自定义拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //可以多个拦截器
//       InterceptorRegistration interceptorDemoRegistration = registry.addInterceptor(new InterceptorDemo());
        //interceptorDemoRegistration.addPathPatterns("/..");
        //interceptorDemoRegistration.addPathPatterns("/..");

        InterceptorRegistration interceptorRegistration = registry.addInterceptor(loginInterceptor);
        //可以设置多个路径拦截
        interceptorRegistration.addPathPatterns("/count");
//        interceptorRegistration.addPathPatterns("/**"); //拦截全部

    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM