1.注解类
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Mytest { String value(); }
2.拦截类
@Configuration public class Login extends WebMvcConfigurerAdapter { @Bean public SessionInterceptor getSessionInterceptor() { System.out.println("bean加载了!"); return new SessionInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { InterceptorRegistration addInterceptor = registry.addInterceptor(getSessionInterceptor()); addInterceptor.addPathPatterns("/**"); } private class SessionInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("==================>"); if(!(handler instanceof HandlerMethod)) { System.out.println(0); return true; } HandlerMethod handlerMethod = (HandlerMethod)handler; Mytest methodAnnotation = handlerMethod.getMethodAnnotation(Mytest.class); if(methodAnnotation == null){ System.out.println(1); return true; } String str = methodAnnotation.value(); System.out.println("拦截value:"+str); System.out.println(2); return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("<=======*=======*========*======华丽的请求分割线======*=========*========*=======>"); } } }
3.使用类
@RestController public class MyController { @Mytest(value = "true") @RequestMapping(value = "/test1/{id}", method = RequestMethod.GET) public String getById(@PathVariable("id") Long id) { System.out.println("请求成功"); return "1"; } @RequestMapping(value = "/test2/{id2}", method = RequestMethod.GET) public String getById2(@PathVariable("id2") Long id2) { System.out.println("请求成功"); return "2"; } }
通过使用@Mytest注解,完成登陆拦截校验.