您的位置:首页 > 编程语言 > Java开发

Spring AOP做权限控制

2018-01-20 13:37 344 查看
最近看项目代码,发现权限管理部分的代码都是直接写在controller层。

那么熟悉Spring的同学很明显发现了,这是典型的可以用切面处理的重复代码。

那么具体怎么处理呢,我先给出我的处理方式:

定义一个注解@Purview

import java.lang.annotation.*;

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Purview {

}

这个注解中什么都不用写,就是用来做切面标记的。

然后写我们的Aspect:

import com.alibaba.fastjson.JSON;
import com.alipay.marketingservice.util.ConstantManager;
import com.alipay.opbiservice.common.Result;
import com.alipay.opbiservice.vo.UserVo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class PurviewAspect {
private static final Logger LOGGER = LoggerFactory.getLogger(LogAspect.class);

/**
* 捕获@Purview注解的方法,在方法执行前进行权限判断
*/
@Before("@annotation(com.alipay.marketingservice.aspect.Purview)")
public void doPurview(JoinPoint point) throws Throwable{
String clazz =point.getTarget().getClass().getName();
// 获取目标对象上正在执行的方法名
String methodName =point.getSignature().getName();
LOGGER.info("开始权限判断:" + clazz + "类的" + methodName + "方法");
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
Result purview = checkPurview(request);
if (null != purview) {
throw new Exception("权限不满足");
}
}

在此,对有@Purview注解的方法做一个权限判断,具体判断方法私有化出来就可以了。

当然,也可以做一些其他操作,这里就不做过多阐述了。

忙的一塌糊涂,这次就写到这里了。O(∩_∩)O~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: