要做一款权限架构,就要适用几个流行的相关框加,struts2是我们公司首先需要考虑的,考虑到侵入性,决定通过切面的方式,在每个Action前进行权限验证,基本思路是:
1,自定义通用权限注解
2,开发抽象切面,预留传入uid的接口
3,配置struts切面,做权限拦截
以下源码是对上边功能的实现:
1,权限注解
/**
* 自定义权限注解
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Authority {
/**
* 权限码
* @return
*/
String authorityCode();
}
2,sturts抽象切面
public abstract class ELInterceptor implements Interceptor {
private IVerificationUser verificationUser;
private ILogicUserAreaFranchiseeService logicUserAreaFranchiseeService;
private Result result = new Result(true);
@Override
public void destroy() {
// TODO Auto-generated method stub
}
protected final Log log = LogFactory.getLog(this.getClass());
@Override
public void init() {
}
/**
* 拦截类并作权限验证
* @param invocation
* @return
* @throws Exception
*/
@Override
public String intercept(ActionInvocation invocation) throws Exception {
log.info("=intercept=>Authority Intercept");
// TODO Auto-generated method stub
String methodName = invocation.getProxy().getMethod();
Method currentMethod = invocation.getAction().getClass().getMethod(methodName);
Method[] methods = invocation.getAction().getClass().getMethods();
initAuthCode(methods);
String isTest = (String) ServletActionContext.getRequest().getParameter("authistest");
//如果该方法请求是需要进行验证的时候执行以下逻辑
if (currentMethod.isAnnotationPresent(Authority.class)) {
//取得权限验证的注解
Authority authority = currentMethod.getAnnotation(Authority.class);
log.info("=intercept=> get authorityCode");
//取得当前请求的注解的authorityCode
String authorityCode = authority.authorityCode();
/* *
* 然后可以在此判断当前用户是否拥有对应的权限,如果没有可以跳到指定的无权限提示页面,如果拥有则可以
* 继续往下执行。
**/
boolean ispass =false;
ispass = Boolean.parseBoolean(getFromVm(authorityCode));
if (ispass){
if(isTest==null ||isTest.trim().isEmpty()){
return invocation.invoke();
}else{
return "hasauth";
}
} else {
log.info("=intercept=> user not have this authorityCode");
writeJson("<html auth='NOAUTH'></html>");
return "noauth";
}
}
log.info("<=intercept=>Authority Intercept");
if(isTest