# SpringBoot Configure the global URL interceptor (login judgment)

SpringBoot configuration global URL interceptor (login judgment)

Define the interceptor: implement the HandlerInterceptor class and rewrite three methods
  • I use the user information in the session to determine whether I have logged in. When I am not logged in, I throw a custom exception NoLoginException, and then go to the global exception handling class to capture this exception and process it. Not to mention the global exception class, the previous blog about global exception handling.
public class UrllInterceptor extends BaseController implements HandlerInterceptor {
    
    

    private Logger logger= Logger.getLogger(UrllInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
        CurrentUser currentUser = getCurrentUser(request);
        String requestURI = request.getRequestURI();
        if(requestURI.contains("/login")){
    
    
            return true;
        } else if(currentUser==null){
    
    
            logger.info("==========当前用户没有登录");
            response.setStatus(201);
            // 抛出没有登录的异常,在全局异常中进行处理
            throw new NoLoginException("没有登录请重新登录!");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    
    

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    
    
        logger.info("==========请求Url:"+request.getRequestURL()+"    "+"==========请求状态:"+response.getStatus());
    }
}

ConfigurationWebMvcConfigurer
  • If you configure druid, swagger and other file upload interfaces, you need to release here
@Configuration
public class UrlConfig implements WebMvcConfigurer {
    
    

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    
        //注册TestInterceptor拦截器
        InterceptorRegistration registration = registry.addInterceptor(new UrllInterceptor());
        registration.addPathPatterns("/**");                      //所有路径都被拦截
        registration.excludePathPatterns(                         //添加不拦截路径
                "你的登陆路径",            //登录
                "/**/*.html",            //html静态资源
                "/**/*.js",              //js静态资源
                "/**/*.css",             //css静态资源
                "/**/*.woff",
                "/**/*.ttf"
        );
    }
}

In short, the implementation is relatively simple, see the code cloud address https://gitee.com/Marlon_Brando/back.git for details

Guess you like

Origin blog.csdn.net/qq_37248504/article/details/108066181