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

12 篇文章 0 订阅

实现权限控制较常用的有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;
	}
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值