自定义注解类
Target 注解可使用位置 类和方法
Retention 生命周期 在运行过程中仍然使用
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckAuth {
boolean check() default true; // 默认需要鉴权
}
拦截器
执行时会先进入preHandle方法,然后通过handler获取类和方法上的注解
public class AuthInterceptor extends HandlerInterceptorAdapter {
...
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod hm = (HandlerMethod) handler;
// 判断类上的注解
boolean check = false;
CheckAuth classAuth = hm.getBeanType().getAnnotation(CheckAuth.class);
if (classAuth != null) {
check = classAuth.check();
}
// 方法是否有注解
CheckAuth methodAuth = hm.getMethodAnnotation(CheckAuth.class);
if (methodAuth != null) {
check = methodAuth.check();
}
if (check) {
UserDTO user = (UserDTO) request.getSession().getAttribute(AuthController.SESSION_USER);
if (user == null) {
response.sendRedirect("/login.html"); // 跳转到登录页面
return false;
}
}
}
return true;
}
...
}
规则
在方法上如果使用了注解,根据方法注解值判断是否鉴权
如果方法上没有注解,获取类上注解,根据注解值判断是否鉴权
使用
@CheckAuth
@Controller
public class IndexController {
@GetMapping("/index")
public String index() {
return "/index";
}
@CheckAuth(check = false)
@GetMapping("/home")
public String home() {
return "/home";
}
}