您的位置:首页 > 编程语言 > Java开发

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

2015-02-02 19:53 661 查看
实现权限控制较常用的有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 {
@Override
public 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;
}
}


如果同时做了两种异常处理,那么只有一种生效,异常一旦拦截,就不会继续传播。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: