1 拦截器HelloWorld
拦截器的使用步骤
- 创建拦截器组件,实现接口Interceptor
- 在struts.xml中注册拦截器
- 在action的配置中引用拦截器
这里我们复用StrutsDay04项目的修改客户功能,并对打开修改页面的action引用自定义的拦截器。
1.3 步骤
步骤一:创建拦截器
创建包interceptor,在该包下创建拦截器组件FirstInterceptor,并实现接口Interceptor,在拦截方法中调用action业务方法,并且在调用action前后分别输出一些内容,以模拟对action请求的拦截。代码如下:
package interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
/**
* 第一个拦截器
*/
public class FirstInterceptor implements Interceptor {
@Override
public void destroy() {
}
@Override
public void init() {
}
@Override
public String intercept(ActionInvocationai) throws Exception {
System.out.println("FirstInterceptor拦截前...");
// 执行action业务方法
ai.invoke();
System.out.println("FirstInterceptor拦截后...");
/*
* 返回值匹配对应的result,但是一旦代码中调用了
* ai.invoke时,则此返回值无效,Struts2会根据
* action的返回值匹配result。如果当前代码中没有
* 调用ai.invoke,则此返回值生效。
* */
return "error";
}
}
步骤二:注册拦截器
步骤三:引用拦截器
在修改客户action的配置下,引用已注册的拦截器,代码如下:
<?xmlversion="1.0"encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<!--客户配置信息 -->
<package name="customer"
namespace="/customer" extends="struts-default">
<interceptors>
<!--注册拦截器 -->
<interceptor name="first"
class="interceptor.FirstInterceptor"/>
</interceptors>
<!--打开修改页面 -->
<action name="toUpdateCustomer"
class="action.ToUpdateCustomerAction">
#cold_bold <!--引用拦截器 -->
#cold_bold <interceptor-ref name="first"/>
<result name="success">
/WEB-INF/customer/update_customer.jsp
</result>
</action>
</package>
</struts>
#cold_bold publicToUpdateCustomerAction() {
#cold_bold System.out.println("实例化ToUpdateCustomerAction...");
#cold_bold }
public String execute() {
#cold_bold System.out.println("调用ToUpdateCustomerAction业务方法...");
}
输出为:实例化ToUpdateCustomerAction...
FirstInterceptor拦截前...
调用ToUpdateCustomerAction业务方法...
FirstInterceptor拦截后...