springboot 拦截器

java

浏览数:86

2019-1-13

//定义拦截器
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        if( httpServletRequest.getSession().getAttribute("loginAdmin")==null){
            if(httpServletRequest.getSession().getAttribute("loginUser")==null){
                throw new NotLoginException("请先登录");
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
//注册拦截器
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new UserInterceptor()).addPathPatterns("/web/**").excludePathPatterns("/web/admin/**","/web/user/login","/web/user/regist");
        super.addInterceptors(registry);
    }
}