本文最后更新于 663 天前,其中的信息可能已经有所发展或是发生改变。
一、定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface NoNeedLogin {
}
二、定义拦截器
@Component
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
boolean isHandlerMethod = handler instanceof HandlerMethod;
if (!isHandlerMethod) {
return true;
}
boolean isNoNeedLogin = ((HandlerMethod) handler).getMethodAnnotation(NoNeedLogin.class)!=null;
if (isNoNeedLogin) {
return true;
}
return false;
}
}
三、添加拦截器
@Configuration
public class WebAppConfig implements WebMvcConfigurer {
@Autowired
private AuthenticationInterceptor authenticationInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authenticationInterceptor);
}
}
四、使用
@ResponseBody
@GetMapping("needLogin")
public String needLogin() {
return "needLogin";
}
@NoNeedLogin
@ResponseBody
@GetMapping("noNeedLogin")
public String noNeedLogin() {
return "noNeedLogin";
}