Struts2的拦截器

最近在学Struts2的拦截器,这里做一个简单的总结。

什么是拦截器

帮助文档中说:

Interceptors are objects that dynamically intercept Action invocations.拦截器是能够动态拦截Action调用的对象。

They provide the developer with the opportunity to define code that can be executed before and/or after the execution of an action.他们使得开发者可以编写一些可以在Action执行方法前后执行的代码。

Interceptors provide developers a way to encapulate common functionality in a re-usable form that can be applied to one or more Actions.拦截器为开发者提供一种提取Action中可重用代码的方式。



设计机制

本质目的:代码复用。

为什么不用继承:灵活性太差,当为Action增加或删除功能时,需修改大量代码。而用拦截器,就可以实现即插即用的效果。


使用拦截器

部署

<interceptors>
	<interceptor name="timer" class="com.opensymphony.xwork2.interceptor.TimerInterceptor"/>
	<interceptor name="logger" class="com.opensymphony.xwork2.interceptor.LoggingInterceptor"/>
	<interceptor name="custom" class="cn.guet.hj.interceptor.CustomInterceptor"/>	
	<interceptor name="methodtest" class="cn.guet.hj.interceptor.MethodInterceptor"/>
			
	<interceptor-stack name="myStack">
		<interceptor-ref name="timer"/>
		<interceptor-ref name="logger"/>
        </interceptor-stack>
</interceptors>
配置

<action name="customAction" class="cn.guet.hj.action.CustomAction">
	<result>/success.jsp</result>
	<interceptor-ref name="custom"/>
</action>


自定义拦截器

方法1:实现Interceptor接口。

方法2:继承AbstractInterceptor类。

String intercept(ActionInvocation invocation)throws Exception

不同之处:继承AbstractInterceptor可以选择性的覆盖方法,如果是实现接口则要实现全部的方法。如果不需要初始化,仅仅覆写intercept方法就可以了。这种情况在Swing中的监听器很常见。


如果只拦截Action的某些方法呢?

<interceptor-ref name="methodtest">
	<param name="excludeMethods">test1</param>
	<param name="includeMethods">test2</param>
</interceptor-ref>
参数 excludeMethods:不用拦截的方法;

参数 includeMethods:需要拦截的方法;


处理Action时等待视图

利用executeAndWait拦截器

<result name="wait">/wait.jsp</result>
<interceptor-ref name="execAndWait"></interceptor-ref>


防止重复提交

1、TokenInterceptor拦截器

原理:在表单页面<s:token/>标记,页面加载时会生成唯一的令牌键值对,执行Action前对比。

步骤:1、在表单中加入token标记

            2、struts中配置

<action name="login" class="cn.guet.hj.action.LoginAction" >
	<result>/success.jsp</result>
	<result name="invalid.token">/repeat.jsp</result>
	<interceptor-ref name="defaultStack"/>
	<interceptor-ref name="token"/>
</action>

2、TokenSessionInterceptor拦截器

步骤:1、在表单中加入token标记

            2、struts中配置

<action name="login" class="cn.guet.hj.action.LoginAction" >
	<result>/success.jsp</result>
	<interceptor-ref name="defaultStack"/>
	<interceptor-ref name="tokenSession"/>
</action>
两种方法的不同之处:

token会当重复提交时会返回invalid.token,从而可以定位到错误页面,但tokenSession则不返回,返回的页面就是第一次提交的页面。


拦截器中运用了动态代理

ActionProxy就是超级代理,通过ActionInvocation调用拦截器。





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值