spring自定义注解

2 篇文章 0 订阅
2 篇文章 0 订阅

spring自定义注解

创建自定义注解

package com.pro.base.oauth;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by zhanghaichao on 2017/5/18.
 * 自定义注解 判断用户权限
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UserPermissions {
    String value() default "blacklist"; //用户权限代码
}

创建注解具体的实现类

package com.pro.base.aop;

import com.pro.base.oauth.UserPermissions;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * Created by zhanghaichao on 2017/5/14.
 * 自定义注解 判断用户权限或者其他用途
 */
//@Aspect 原来使用注解来添加切面后改成xml配置
//@Component
public class UserPermissionsAspect {
    private Logger logger = LoggerFactory.getLogger(getClass());

    //要用&&链接否则没有注解的地方也将被切入
//    @Pointcut("execution(public * com.base.core.web.*Controller.*(..))&&@annotation(com.base.core.oauth.UserPermissions)")
//    public void permission() {
//    }

    /**
     * 获取用户权限代码进行比对
     *
     * @param joinPoint
     * @throws Throwable
     */
//    @Before("permission()")
    //这里的方法参数也可以用ProceedingJoinPoint 这个的继承是JoinPoint
    public void doBefore(JoinPoint joinPoint) throws Throwable {

        ServletRequestAttributes attributes = (ServletRequestAttributes)          RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        String permissions = "";
        if (method.isAnnotationPresent(UserPermissions.class)) {
            UserPermissions userPermissions = method.getAnnotation(UserPermissions.class);
            permissions = userPermissions.value();
        }

        boolean hasRole = false;
        boolean blackList = false;
        boolean rooter = false;
        try {
            String[] userRole = (String[]) request.getSession().getAttribute("userRole");
            for (String role : userRole) {
                if (role.equals(permissions)) {
                    hasRole = true;
                }
                //最高权限判断  后面放在配置文件里
                if (role.equals("root")) {
                    rooter = true;
                }
                //黑名单判断 后面放在配置文件里
                if (role.equals("blacklist")) {
                    blackList = true;
                }
            }
            //如果黑名单
            if (blackList) {
                this.unauthorized(attributes);
            } else if (rooter || hasRole) {
                logger.info("UserPermission : " + permissions);
            } else {
                this.unauthorized(attributes);
            }
        } catch (Exception e) {
            this.unauthorized(attributes);
        }
    }

    /**
     * 未授权,则跳转到错误页
     *
     * @param sra ServletRequestAttributes
     * @throws Throwable 跳转异常
     */
    private void unauthorized(ServletRequestAttributes sra) throws Throwable {
        HttpServletResponse response = sra.getResponse();
        logger.info("失败");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "没有登录或登录已超时!");

    }
}

在xml里配置

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">



    <!--用户权限控制aop-->
    <bean id="userPermissions" class="com.pro.base.aop.UserPermissionsAspect"/>
    <aop:config>
        <aop:aspect id="userPermissions-aspect" ref="userPermissions">
            <aop:pointcut id="UserPermissionMgr"
                          expression="(execution(public * com.base.core.web.*Controller.*(..)))&amp;&amp;(@annotation(com.pro.base.oauth.UserPermissions))"/>
            <aop:before method="doBefore" pointcut-ref="UserPermissionMgr"/>
        </aop:aspect>
    </aop:config>
    <!--用户权限控制aop END-->
</beans>

完工

附上自己的项目链接大家可以用来练手使用

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值