环境准备
- 员工已经登入.
- 将员工对应的权限表达式集合存入session,(EXPS_IN_SESSION)
检查权限拦截器
放行条件:
- 该Action不需要权限就可以访问 (访问的方法,没有被注解)
- 该员工是超级管理员
- 该员工拥有此权限 (session中的权限表达式列表,有访问的方法对应的表达式)
public class PermissionCheckInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
//是否需要爱权限
//是否是超级管理员
//是否拥有该权限
if(isNoRequired(invocation)||isAdmin(invocation)||isHasPermission(invocation)) {
invocation.invoke();
}
return "noPermission";
}
//请求的Action是否需要权限
private boolean isNoRequired(ActionInvocation invocation) throws Exception {
//获取方法对象
Method method = this.getMethod(invocation);
//若没被注解,则返回true(放行)
if(!method.isAnnotationPresent(RequiredPermission.class)) {
return true;
}
return false;
}
//是否是超级管理员
private boolean isAdmin(ActionInvocation invocation) {
//获取当前session中的employee对象
Employee employee = (Employee) ActionContext.getContext().getSession().get("EMPLOYEE_IN_SESSION");
//admin属性是boolen类型
return employee.getAdmin();
}
//是否拥有该权限
//该判断排在最后,所以访问的Action必然被注解(没被注解直接pass了)
private boolean isHasPermission(ActionInvocation invocation) throws Exception {
//当前访问Action的权限表达式
Method method = this.getMethod(invocation);
String EXP = PermissionUtil.creatEXP(method);
//获得角色拥有的权限的表达式集合
Set<String> EXPs = (Set<String>) ActionContext.getContext().getSession().get("EXPS_IN_SESSION");
if(EXPs.contains(EXP)) {
return true;
}
return false;
}
//获取当前访问的Action对应的方法对象
private Method getMethod(ActionInvocation invocation) throws Exception {
Class<?> clz = invocation.getProxy().getAction().getClass();
return clz.getMethod(invocation.getProxy().getMethod());
}
}
配置文件的部署
- 该拦截器要部署在登入拦截器之后,(登入后才能保证session中有对象.,免去判断null的情况)
<interceptors>
<!--声明登入拦截器+权限拦截器-->
<interceptor name="loginInterceptor" class="interceptor.LoginInterceptor">
<param name="excludeActions">login_login</param>
</interceptor>
<interceptor name="permissionCheckInterceptor" class="interceptor.PermissionCheckInterceptor"></interceptor>
<!--生成拦截器stack-->
<interceptor-stack name="myStack">
<interceptor-ref name="loginInterceptor"/>
<interceptor-ref name="permissionCheckInterceptor"/>
<interceptor-ref name="paramsPrepareParamsStack"/>
</interceptor-stack>
</interceptors>
<!--使用拦截器-->
<default-interceptor-ref name="myStack"/>