Struts2拦截器

拦截器的使用步骤:

1、创建一个类,实现Interceptro接口,并其中的intercept方法。

2、在配置文件中通过<interceptors></interceptors>声明拦截器。

3、通过<interceptor-ref>引用拦截器。

一下为用拦截器实现简单的权限控制:

Action:

public class InterceptorAction extends ActionSupport{
	
	public String saveUser(){
		System.out.println("Save User");
		return "privilege";
	}

}
Interceptor:

public class PrivilegeInterceptor implements Interceptor{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		String username = ServletActionContext.getRequest().getParameter("username");
		if("admin".equals(username)){
			invocation.invoke();
			return "privilege";
		}else{
			ActionContext.getContext().put("message", "权限不足,无法添加用户!");
			return "privilege";
		}
	}

}
配置文件:

<interceptors>
			<!-- 声明拦截器 -->
			<interceptor name="privilegeInterceptor" class="cn.itcast.interceptor.PrivilegeInterceptor"></interceptor>
			
			<!-- 声明拦截器栈 -->
			<interceptor-stack name="privilegeStack">
				<interceptor-ref name="defaultStack"></interceptor-ref>
				<!-- 引用拦截器 -->
				<interceptor-ref name="privilegeInterceptor"></interceptor-ref>
			</interceptor-stack>
		</interceptors>
		<!-- 通过拦截器栈使用拦截器 -->
		<default-interceptor-ref name="privilegeStack"></default-interceptor-ref>
		
		<action name="interceptor_*"  method="{1}" class="cn.itcast.inteceptorAction.InterceptorAction">
			<result name="privilege">interceptor.jsp</result>
		</action>
interceptor.jsp:

<s:form action="interceptor_saveUser.action">
		<s:textfield name="username"></s:textfield>
		<s:submit></s:submit>
	</s:form>
	
	<s:if test="#message!=null">
		<s:property value="#message"/>
	</s:if>
拦截器的意义:可以把一些和业务逻辑没有关系的代码放到拦截器中,做到这些代码和业务逻辑的松耦合。

拦截器的执行顺序:按拦截器在拦截器栈中定义的顺序,从上往下执行。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值