Spring使用自定义注解和拦截器实现鉴权

自定义注解类

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";
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值