1. Inheritance HandlerInterceptorAdapter class and realize the preHandler () method, the request of the intercepted before calling the controller layer will call first preHandler () method is the first step in processing the request.
public class LoginInterceptor extends HandlerInterceptorAdapter { private static final Logger logger = LoggerFactory.getLogger(LoggerFactory.class); @Autowired private CookieUtil cookieUtil; /* param request * @param Response * @param handler * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("preHandler"); // The controller method modified by @requestMapping is HanglerMethod // a.isAssignableFrom (B), which checks whether A is the same class as B, and whether A isA superclass or superinterface of Btrue, no returnfalse
        if(! handler.getClass().isAssignableFrom(HandlerMethod.class)) { System.out.println("cat cast handler to HandlerMethod.class");
            return true; } HandlerMethod method = (HandlerMethod)handler; / / get in the way that the controller annotation NeedLogin NeedLogin = method. The getMethodAnnotation (NeedLogin. Class);if (needLogin == null){
            return true;
        }

        String paramToken = request.getParameter(CookieUtil.COOKIE_NAME);
        String cookieToken = cookieUtil.getLoginToken(request);
        if (StringUtils.isEmpty(paramToken) && StringUtils.isEmpty(cookieToken)){
            return false;
        }
        String token = paramToken == null ? cookieToken:paramToken;
        SecondKillUser user = cookieUtil.getUserByToken(token,response);
        return  user == null ? false : true;
    }

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

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }
Copy the code
  1. Register the interceptor and put the interceptor class into the Spring container, otherwise you cannot inject other beans
@configuration public class WebConfig extends WebMvcConfigurerAdapter {/** * register interceptor / @override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginInterceptor()).addPathPatterns("/ * *");
    }

    @Bean
    public LoginInterceptor loginInterceptor() {returnnew LoginInterceptor(); }}Copy the code