这是用spring aop 实现的一个权限控制,已注解为主。
一共有2个类, 1个类是注解,另一个就是切面类了:
以下是具体代码:
这是个注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Authentication {
/**
<span style="white-space:pre"> </span> * 用于权限控制,如果string[]里包含用户组名字,则验证成功
<span style="white-space:pre"> </span> */
String[] need();
}
下面是切面类的方法:
public Object invoke(MethodInvocation invocation) throws Throwable {
//如果方法未被注解则通过
if(!invocation.getMethod().isAnnotationPresent(Authentication.class)){
return invocation.proceed();
}
//从session里取出当前用户的信息
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession();
String roleName = ((LoginInfo) session.getAttribute("loginInfo")).getRole().getRoleName();
Authentication authentication = invocation.getMethod().getAnnotation(Authentication.class);
String[] needs = authentication.need();
//检查权限,未通过则抛出异常
if(needs!=null&&needs.length>0&&needs[0].length()>0){
for(String s:needs){
if(roleName.equals(s)){
return invocation.proceed();
}
}
throw new PermissionDeniedException("权限不足");
}
return invocation.proceed();
}
想要某个方法被审查只要在方法前面加上 @Authentication(need="XX") 就行。