自定义拦截器1
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class MyInterceptor1 implements Interceptor {
@Override
public void destroy() {
}
@Override
public void init() {
}
@Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("1 执行interceptor1的action前面的代码!");
String result = invocation.invoke();
System.out.println("5 执行interceptor1的action后面的代码!");
return result;
}
}
自定义拦截器2
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class MyInterceptor2 implements Interceptor {
@Override
public void destroy() {
}
@Override
public void init() {
}
@Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("2 执行interceptor2的action前面的代码!");
String result = invocation.invoke();
System.out.println("4 执行interceptor2的action后面的代码!");
return result;
}
}
action类
import com.opensymphony.xwork2.ActionSupport;
//图书操作类
public class BookAction extends ActionSupport {
//接收页面参数
private String name;
public void setName(String name) {
this.name = name;
}
private String password;
public void setPassword(String password) {
this.password = password;
}
public String list(){
System.out.println("3 执行了图书的list方法!");
System.out.println(name);
System.out.println(password);
return SUCCESS;
}
}
在struts.xml文件中配置拦截器,并定义拦截器栈。
注意:在配置action时,引用了自定义的拦截器栈后,默认的拦截器栈(defaultStack)也要引用,并且放在配置的第一位置。否则,struts2的很多核心功能将失效。例如不能接收页面传过来的参数。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="interceptor" extends="struts-default" namespace="/interceptor">
<!-- 配置自定义拦截器 -->
<interceptors>
<!-- 定义拦截器 -->
<interceptor name="interceptor1" class="edu.scut.d_Interceptor.MyInterceptor1"/>
<interceptor name="interceptor2" class="edu.scut.d_Interceptor.MyInterceptor2"/>
<!-- 定义拦截器栈 -->
<interceptor-stack name="myStack">
<!-- 一个拦截器栈包含多个拦截器 -->
<!-- 注意:struts2的默认拦截器一定要配置在第一位!否则会被覆盖! -->
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="interceptor1"></interceptor-ref>
<interceptor-ref name="interceptor2"></interceptor-ref>
</interceptor-stack>
</interceptors>
<action name="book_*" class="edu.scut.d_Interceptor.BookAction" method="{1}" >
<!-- 引入拦截器 -->
<interceptor-ref name="myStack"></interceptor-ref>
<result >/succ.jsp</result>
</action>
</package>