这里主要记录一下拦截器。
Struts2里的拦截器interceptor类似于Servlet里的过滤器filter,如果加入拦截器,则struts2的一般流程(不包含其他情况)为:
服务接收到客户端请求----》查看web.xml文件,进入struts2控制----》查看struts.xml文件----》进入拦截器 ---》进行类型转换converter----》执行action类的set方法----》执行验证框架----》执行验证类----》执行action类里的validate方法----》执行action类里的execute方法-----》退出拦截器。
现在来编写一个简单的说明例子。
1、新建一个包com.xbb.interceptor,在该包下新建一个类FirstInterceptor,让其实现Interceptor接口:
package com.xbb.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class FirstInterceptor implements Interceptor {
private String testparam;
public String getTestparam() {
return testparam;
}
public void setTestparam(String testparam) {
this.testparam = testparam;
}
public void destroy() {
// TODO Auto-generated method stub
System.out.println("firstinterceptor detory");
}
public void init() {
// TODO Auto-generated method stub
System.out.println("first interceptor init");
System.out.println("init testparam:"+ testparam);
}
public String intercept(ActionInvocation invocation) throws Exception {
// TODO Auto-generated method stub
System.out.println("first intercept()");
String result = invocation.invoke();
System.out.println("first result:" + result );
//System.out.println("intercept testparam:"+ testparam);
return result;
}
}
2、在struts.xml里配置拦截器,分两步:
------2.1声明拦截器:
<interceptors>
<interceptor name="firstInterceptor" class="com.xbb.interceptor.FirstInterceptor">
<param name="testparam">xbb</param>
</interceptor>
</interceptors>
其中<param>子元素存放参数,只要在拦截器类里定义相应的set方法,就能在初始化拦截器时自动获取参数。
-----2.2使用拦截器:
<action name="docommit" class="com.xbb.action.DoCommit">
<result name="success">/result.jsp</result>
<result name="input">/commit.jsp</result>
<interceptor-ref name="firstInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>
defaultStack是启用struts默认的拦截器栈。
至此完毕。
本文详细介绍了Struts2框架中的拦截器概念及其工作流程,并通过一个实例演示了如何自定义拦截器,包括创建拦截器类、配置拦截器以及如何在Struts.xml中声明和使用这些自定义拦截器。

3487

被折叠的 条评论
为什么被折叠?



