The interceptor

1. HandlerInterceptor interface
/** * Implements the HandlerInterceptor interface */
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        HashMap<String, Object> map = new HashMap<>();

        try {
            JWTUtils.verify(token);
            return true;
        } catch (TokenExpiredException e) {
            map.put("state".false);
            map.put("msg"."Token has expired");
        }catch (SignatureGenerationException e){
            map.put("state".false);
            map.put("msg"."Wrong signature!");
        }catch (AlgorithmMismatchException e){
            map.put("state".false);
            map.put("msg"."Encryption algorithms don't match!");
        }catch (Exception e){
            map.put("state".false);
            map.put("msg"."Invalid token!");
        }

        JSON json = JSONUtil.parse(map);
        response.setContentType("application/json; utf-8");
        response.getWriter().println(json);
        return false; }}Copy the code
2. Configure interceptors
/** * The interceptor is registered in the container (addInterceptors for WebMvcConfigurer) */
@Component
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new JwtInterceptor())
          .addPathPatterns("/ * *")
                .excludePathPatterns("/user/**"); }}Copy the code

Principle of interceptor

1. Find the **HandlerExecutionChain based on the current request.

2. Execute the preHandle method of all interceptors in sequence first

  • 1. If the current interceptor preHandler returns true. The preHandle of the next interceptor is executed
  • 2. If the current interceptor returns false. Execute afterCompletion directly in reverse order for all already executed interceptors;

If either interceptor returns false, the target method is not executed. All interceptors return True, execute the target method, and then execute all interceptors’ postHandle methods in reverse order

4. Any exception to the previous steps will trigger afterCompletion directly in reverse order; AfterCompletion is also triggered in reverse order after the page has successfully rendered