具体方法是在action中的访问方法上加上自定义注解,在拦截器中,根据用户角色是否具有自定义注解中指定的权限,来选择向用户呈现的内容。
注解类实现:
package com.hurricane.shop.util;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* 自定义注解
*/
//被这个注解修饰的注解,利用反射,将其他的注解读取出来
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationLimit {
String mid(); //子模块模块名称
String pid(); //父模块操作名称
}
拦截器中判断的相关代码:
HttpServletRequest request = (HttpServletRequest) actioninvocation
.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);
//获取请求的action对象
Object action = actioninvocation.getAction();
//获取请求的方法的名称
String methodName = actioninvocation.getProxy().getMethod();
//获取action中的方法的封装类(action中的方法没有参数)
Method method = action.getClass().getMethod(methodName, null);
String result = null; // Action的返回值
//在完成跳转Action之前完成细颗粒权限控制,控制Action的每个方法
//检查注解,是否可以操作权限的URL
boolean flag = isCheckLimit(request,method);
if(flag){
// 运行被拦截的Action,期间如果发生异常会被catch住
result = actioninvocation.invoke();
}
else{
request.setAttribute("errorMsg", "对不起!您没有权限操作此功能!");
return "errorMsg";
}
return result;
/**验证细颗粒权限控制*/
public boolean isCheckLimit(HttpServletRequest request, Method method) {
if(method==null){
return false;
}
//获取当前的登陆用户
ElecUser elecUser = (ElecUser)request.getSession().getAttribute("globle_user");
if(elecUser==null){
return false;
}
//获取当前登陆用户的角色(一个用户可以对应多个角色)
Hashtable<String, String> ht = (Hashtable)request.getSession().getAttribute("globle_role");
if(ht==null){
return false;
}
//处理注解,判断方法上是否存在注解(注解的名称为:AnnotationLimit)
/*
* 例如:
* @AnnotationLimit(mid="aa",pid="0")
public String home(){
*/
boolean isAnnotationPresent= method.isAnnotationPresent(AnnotationLimit.class);
//不存在注解(此时不能操作该方法)
if(!isAnnotationPresent){
return false;
}
//存在注解(调用注解)
AnnotationLimit limit = method.getAnnotation(AnnotationLimit.class);
//获取注解上的值
String mid=limit.mid(); //权限子模块名称
String pid=limit.pid(); //权限父操作名称
/**
* 如果登陆用户的角色id+注解上的@AnnotationLimit(mid="aa",pid="0")
* * 在elec_role_popedom表中存在 flag=true,此时可以访问Action的方法;
* * 在elec_role_popedom表中不存在 flag=false,此时不能访问Action的方法;
*/
boolean flag=false;
//拦截器中加载spring容器,从而获取Service类,使用Service类查询对应的用户信息
WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
IElecRoleService elecRoleService = (IElecRoleService)wac.getBean(IElecRoleService.SERVICE_NAME);
//查询elec_role_popedom表中的所有的数据,使用二级缓存,解决系统性能问题
List<ElecRolePopedom> list = elecRoleService.findAllRolePopedomWithCache();
if(list!=null&&list.size()>0){
for(int i=0;i<list.size();i++){
ElecRolePopedom elecRolePopedom = list.get(i);
if(elecRolePopedom!=null){
if(ht!=null && ht.size()>0){
for(Iterator<Entry<String, String>> ite = ht.entrySet().iterator();ite.hasNext();){
Entry<String, String> entry = ite.next();
//获取角色ID
String roleID = entry.getKey();
if(roleID.equals(elecRolePopedom.getRoleID()) && mid.equals(elecRolePopedom.getMid())
&& pid.equals(elecRolePopedom.getPid())){
//flag=true:表示有权限操作该功能
flag=true;
break;
}
}
}
}
}
}
return flag;
}