《权限控制系列3》----利用拦截器匹配URL

前言

  • 权限的粒度可以细细的划分,甚至可以划分到代码中的每个方法上面,只要用户没有权限访问某个CRUD的方法,我们可以将其拦截。

总体思路

  • 添加全局的拦截器,拦截用户的请求,判断用户是否有请求此方法的权限,若用户有权限,则放行,若用户没有权限,则拦截,提示用户没有权限使用此功能。

自定义注解代码

@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationLimit {
    String mid();
    String pid();
}

拦截器代码

public class ErrorAndLimitInterceptor extends MethodFilterInterceptor {

    /**拦截器*/
    @Override
    protected String doIntercept(ActionInvocation actioninvocation) throws Exception {
        //把自定义错误信息 放置到request中
        HttpServletRequest request = (HttpServletRequest) actioninvocation
                        .getInvocationContext().get(StrutsStatics.HTTP_REQUEST);
        try {
            //获取请求的action对象
            Object action = actioninvocation.getAction();
            //获取请求的方法的名称
            String methodName = actioninvocation.getProxy().getMethod();
            //获取action中的方法的封装类(action中的方法没有参数)
            Method method = action.getClass().getMethod(methodName, null);
            // Action的返回值   
            String result = null; 
            boolean flag=isCheckLimit(request,method);
            if (flag) {
                //运行被拦截的Action,如果期间发生异常会被catch住
                result=actioninvocation.invoke();
            }else{
                request.setAttribute("errorMsg", "对不起,您没有权限操作此功能");
                return "errorMsg";
            }
            return result;
        } catch (Exception e) {
            /**  
             * 处理异常  
             */
            String errorMsg = "出现错误信息,请查看日志!";
            //通过instanceof判断到底是什么异常类型   
            if (e instanceof RuntimeException) {
                //未知的运行时异常   
                RuntimeException re = (RuntimeException) e;
                //re.printStackTrace();
                errorMsg = re.getMessage().trim();
            }
            /**  
             * 发送错误消息到页面  
             */
            request.setAttribute("errorMsg", errorMsg);

            /**  
             * log4j记录日志  
             */
            Log log = LogFactory
                    .getLog(actioninvocation.getAction().getClass());
            log.error(errorMsg, e);
            return "errorMsg";
        }  
    }


    private 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<String, String>) request.getSession().getAttribute("globle_role");
        if (ht==null) {
            return false;
        }

        //处理注解,判断方法上是否存在注解
        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 注解上的mid pid 查询数据库中该角色是否用于此方法的权限

        boolean flag=false;
        //拦截器中加载spring容器,从而获取Service类,使用Service类查询对应的用户信息
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
        IElecRoleService elecRoleService = (IElecRoleService)wac.getBean(IElecRoleService.SERVICE_NAME);
        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();
                flag=elecRoleService.findRolePopedomByID(roleId,mid,pid);
                if (flag) {
                    break;
                }
            }
        }
        return flag;
    }

}

拦截器配置

<interceptors>
   <!-- 声明拦截器 -->
   <interceptor name="errorAndLimitInterceptor" class="com.itheima.elec.utils.ErrorAndLimitInterceptor" />
   <!-- 配置拦截器栈 -->
   <interceptor-stack name="myErrorAndLimitInterceptor">
    <interceptor-ref name="defaultStack" />
      <interceptor-ref name="errorAndLimitInterceptor" >
      <param name="excludeMethods">menuHome,title,left,change,loading,logout,alermStation,alermDevice,showMenu
      </param>
      </interceptor-ref>
   </interceptor-stack>
</interceptors>
<!-- 覆盖底层的拦截器栈 对包中的所有action都有效 -->
<default-interceptor-ref name="myErrorAndLimitInterceptor"/>

在方法上添加权限的注解

@AnnotationLimit(mid="an",pid="am")
    public String home() {
        方法体
        .......
        .......
        return "home";
    }

小结

  • 拦截器中代码的功能是读取方法体上的注解代码,注解代码中存放着访问此方法的权限信息,用户拿到这些权限信息后,再加上自己角色id,然后利用这些信息一块去数据库中检查该用户是否拥有此权限,若有,则放行,反之则拦截。做到这,我们将权限的粒度控制在每个方法上面了,我们再在浏览器中的地址栏中输入Url地址也不会访问到非法页面了。
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值