您的位置:首页 > 其它

使用拦截器和自定义注解实现权限控制

2013-12-06 18:03 281 查看
使用注解为每个Action的方法声明权限。
1.首先创建自定义注解,用于设置权限:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface PrivilegeControll {
//权限的名称,可能有很多个权限,所以用数组表示
String[] privilegeName();
}
2.在需要权限控制的action上面添加注解
@PrivilegeControll(privilegeName="增加章节")
@Action(value="toAddChapter",results={@Result(location="/WEB-INF/common/addChapter.jsp")})
public String toAddChapter() throws Exception{
return SUCCESS;
}
如果有两个或者以上的权限可以写成
@PrivilegeControll(privilegeName={"增加章节","修改章节"})
@Action(value="getChapterNo",results={@Result(type="json",params={"root","json"})})
public String getChapterNo() throws Exception{.....}
3.添加拦截器
public class CheckLoginInterceptor extends MethodFilterInterceptor{
@Override
protected String doIntercept(ActionInvocation invocation) throws Exception {
//获取action方法名称
String methodName = invocation.getProxy().getMethod();
//得到Method对象
Method method = invocation.getAction().getClass().getMethod(methodName);
//如果方法存在,并且该方法添加了我们自定义的注解
if(method != null && method.isAnnotationPresent(PrivilegeControll.class)){
//获取注解对象
PrivilegeControll privilegeControll = method.getAnnotation(PrivilegeControll.class);
//获取访问该方法需要的权限的名称
String[] privilegeName = privilegeControll.privilegeName();
for(Privilege privilege : role.getPrivileges()){
for(int i = 0;i<privilegeName.length;i++){


//如果拥有权限则放行 if(privilegeName[i].equals(privilege.getPrivilegeName())){

return invocation.invoke();
}
}
}
}
}
//否则返回没有权限的视图
return "noPrivilege";
}

}

4.配置noPrivilege的视图
<global-results>
<result name="login" type="redirect">/login.jsp</result>
<result name="input">/error.html</result>
<result name="noPrivilege">/noPrivilege.html</result>
</global-results>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: