struts2利用异常处理实现权限控制的两种方法

来源:互联网 发布:c语言不合法标识符 编辑:程序博客网 时间:2024/06/06 05:09

实现权限控制较常用的有shiro,shiro一般用于方法级别的松散权限控制,这种权限控制的原理是基于权限判断后抛出异常,比如checkPermission("wage:listself"),是校验权限串wage:listself,如果没有该权限,则抛出异常,比如checkRole("超级用户"),是校验角色,如果没有该角色也会抛出异常,这些都可以改为基于注释的形式应用于方法上。此时,可以通过进行异常的处理,来将页面导向到提示未授权的页面。而struts2中异常处理可以有两种方式,一种是在struts.xml中配置异常处理。另一种是通过自定义一个拦截器,来处理异常。下面是核心代码:

第一种:注意global-results必须在前

<package name="banit-default" extends="struts-default"><global-results><result name="UnauthorizedException">/unAuthorized.jsp</result></global-results><global-exception-mappings><exception-mapping result="UnauthorizedException"exception="org.apache.shiro.authz.UnauthorizedException"></exception-mapping><exception-mapping result="UnauthorizedException"exception="org.apache.shiro.authz.AuthorizationException"></exception-mapping></global-exception-mappings></package>
第二种:

<package name="banit-default" extends="struts-default"><interceptors><interceptor name="exceptionInterceptor"class="cn.banit.lycz.web.ExceptionInterceptor" /><!-- 定义一个拦截器栈 --><interceptor-stack name="myInterceptor"><interceptor-ref name="exceptionInterceptor" /><interceptor-ref name="defaultStack" /></interceptor-stack></interceptors><default-interceptor-ref name="myInterceptor" /></package>

ExceptionInterceptor:

public class ExceptionInterceptor extends AbstractInterceptor {@Overridepublic String intercept(ActionInvocation arg0) throws Exception {try {arg0.invoke();} catch (UnauthorizedException e) {String contextPath = ServletActionContext.getRequest().getContextPath();ServletActionContext.getResponse().sendRedirect(contextPath + "/unAuthorized.jsp");} catch (Exception e) {System.err.println("Exception:" + e.getLocalizedMessage());}return null;}}

如果同时做了两种异常处理,那么只有一种生效,异常一旦拦截,就不会继续传播。

0 0
原创粉丝点击