Struts2讲义7(转载)
扩展拦截器接口的自定义拦截器配置
技术要点
本节代码介绍拦截器基础配置以及设置参数功能。
?
? Action配置中拦截器参数定义和注意点。
? 拦截器参数的设置和配置修改过程。
演示代码
- <!-------------------------------文件名:ExampleInterceptor.java------------------------->import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.Interceptor;public class ExampleInterceptor implements Interceptor {//设置新参数private String newParam;public String getNewParam() {return newParam;}public void setNewParam(String newParam) {this.newParam = newParam;}public void destroy() {System.out.println("end doing...");}//拦截器初始方法public void init() {System.out.println("start doing...");System.out.println("newParam is:"+newParam);}//拦截器拦截方法public String intercept(ActionInvocation arg0) throws Exception {System.out.println("start invoking...");String result = arg0.invoke();System.out.println("end invoking...");return result;}}
拦截器映射配置。
- <!-------------------------------------文件名:struts.xml-----------------------><!-- 拦截器配置定义 --><interceptors><interceptor name="example"><result name="input">/jsp/login.jsp</result><result name="success">/jsp/success.jsp</result><!-- Action中拦截器定义 --><interceptor-ref name="example"><!-- 改变拦截器参数值 --><param name="newParam">example</param></interceptor-ref></action>
执行效果如图4.2所示。
图4.2? 执行拦截器后效果
参数值显示如图4.3所示。
图4.3? newParam参数值显示图
代码解释
(1)先看struts.xml文件,在文件开始以<interceptors>开头,</interceptors>结尾形式定义了拦截器,该拦截器命名为example,映射的类文件路径写在class属性中。在<Action>中<result>标签后,可以定义只在该Action执行时候会拦截的拦截器定义,其实就是调用在<Action>前定义的example拦截器。并且还可以以<param>标签定义拦截器属性。
(2)<param>标签定义拦截器属性,或者称为参数。param其实就是英语中参数缩写形式。name是参数名,而在<param></param>间的内容就是该定义的参数值。
注意:如果在<Action>中和<Action>外都定义<param>的值,比如在本实例中<Action>中newParam值为“example”,<Action>外newParam值为“test”。而在运行时候显示的还是<Action>中的参数值,即“example”。显示如图4.3。可以理解为屏蔽了<Action>外参数值,因此如果定义多个Action,每个Action都调用了example拦截器,则都可以自定义自己的newParam的值了。如果不定义的话,那显示的就是“test”,否则就是各自定义的newParam值。
(3)再来看看ExampleInterceptor类代码,newParam是它的一个私有变量属性,有自己的setter、getter方法。而且它扩展了Interceptor接口,该接口是Struts2的类库中自带的接口类。重写interceptor方法,用invoke方法执行Action,在Action前后执行两个打印方法。
启动服务器后,在网页上显示登录页面,单击“登录”,然后在MyEclipse的控制台下就可以看见如图4.2显示的效果图。如果读者能看见这两行字被打印出来,就说明example拦截器拦截Login Action成功。