Define a custom annotation

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserAuthorization {

}
Copy the code

The @target annotation resolves which components the custom annotation can load, such as methods, classes, and properties

  • TYPE class, interface (including annotation TYPE), or enumeration declaration
  • FIELD FIELD declarations (including enumeration constants)
  • METHOD METHOD declaration
  • PARAMETER Specifies the PARAMETER form
  • CONSTRUCTOR CONSTRUCTOR declaration
  • LOCAL_VARIABLE Local variable declaration
  • ANNOTATION_TYPE Annotation type declaration
  • PACKAGE bag
  • TYPE_PARAMETER Specifies the type parameter
  • TYPE_USE Use type

The Retention annotation determines the lifetime of this custom annotation

  • SOURCE Annotations exist only in Java source filesComments will be discarded after compilation
  • The annotations are still there when the CLASS is compiled into a.class file, but are not there when the CLASS loader loads them into memory
  • RUNTIME annotations have a life cycle that lasts as long as the program is running and can be read reflectively

Configure an interceptor

@Configuration public class WebAppConfig implements WebMvcConfigurer { @Override public void AddInterceptors (InterceptorRegistry registry) {/ * * * add interceptors * / registry. AddInterceptor (new AuthorizationInterceptor2 ()) .addPathPatterns("/api/**"); }}Copy the code

Implementation of interceptors

Public class AuthorizationInterceptor2 extends HandlerInterceptorAdapter {/ * * * the Request of the Key Key * / public static final String REQUEST_CURRENT_KEY ="REQUEST_CURRENT_KEY"; /** * Private String httpHeaderName ="sessionId"; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object Handler) throws Exception {/** * if it is not mapped to a method directly pass */if(! (handler instanceof HandlerMethod)) {return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        String token = request.getHeader(httpHeaderName);
        if(token ! = null && token.length() > 0) {/** ** return key based on token if not nulltrue
             */
            String key = "";
            if(key ! = null) { request.setAttribute(REQUEST_CURRENT_KEY, key);return true; } /** * If the token validation fails and the method or class is specified with Authorization, an error */ is returnedif(method.getAnnotation(Authorization.class) ! = null || handlerMethod.getBeanType().getAnnotation(Authorization.class) ! = null) { throw new ApiException(ApiConstants.SESSIONIDEXCEPTION,"Permission exception");
        }
        request.setAttribute(REQUEST_CURRENT_KEY, null);
        return true; }}Copy the code

This allows you to add UserAuthorization to a class or method for permission control