java注解简单实现权限控制

注解:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RoleAnnotation {
    RoleEnum value();
}

注解实现:

@Aspect
@Component
public class roleAspect {
    @Pointcut("@annotation(“这里写注解的路径”)")
    public void annotationPointCut(){

    }

    @Around(value ="annotationPointCut()")
    public Object advice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Signature signature = proceedingJoinPoint.getSignature();//此处joinPoint的实现类是MethodInvocationProceedingJoinPoint
        MethodSignature methodSignature = (MethodSignature) signature;//获取参数名
        RoleAnnotation data = methodSignature.getMethod().getAnnotation(RoleAnnotation.class);
        String value = data.value().getCode();
       //获取session
        HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session =request.getSession();
        Object obj = session.getAttribute("monitoring");
        String [] monitoring = obj.toString().split(",");
        List<String> list = Arrays.asList(monitoring);
        if(list.contains(value)){
            return proceedingJoinPoint.proceed();
        }
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("rspmsg","系统权限不足");
        return map;
    }
}

枚举类:

public enum RoleEnum {
 CESHI("1","test","qqq")
    , DFSFS("2","test1",""),
    GSDFGSG("3","test2","123"),
    WERWERWE("4","test3","123"),
    GSDSFDS("5","test4","123");
    private String code;
    private String msg;
    private String key;

     RoleEnum(String code, String msg,String key)
    {
        this.code=code;
        this.msg=msg;
        this.key=key;
    }

    public String getMsg()
    {
        return this.msg;
    }
    public String getCode() {
        return this.code;
    }
    public String getKey() {
        return this.key;
    }
}

然后Controller上加上就可以了验证了
@RoleAnnotation(RoleEnum.CESHI)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容