拦截器的实现主要靠得是一个拦截器链,另外的一个是拦截器的调用的类,它的目的就是在真正执行Action方法之前加入一些额外的处理代码
Action类
public class Action {
public String execute() {
return "success";
}
}
拦截器接口:
public interface Interceptor {
public void intercept(ActionInvocation invocaion);
}
拦截器实现类1
public class FirstInterceptor implements Interceptor {
@Override
public void intercept(ActionInvocation invocaion) {
System.out.println("first before");
invocaion.invoke();
System.out.println("first end");
}
}
拦截器实现类2
public class SecondInterceptor implements Interceptor {
@Override
public void intercept(ActionInvocation invocaion) {
System.out.println("second before");
invocaion.invoke();
System.out.println("second end");
}
}
ActionInvocation类
public class ActionInvocation {
private List<Interceptor> interceptors=new ArrayList<Interceptor>();
private int index=-1;
Action action = new Action();
public ActionInvocation() {
interceptors.add(new FirstInterceptor());
interceptors.add(new SecondInterceptor());
}
public void invoke() {
index++;
if(index>=interceptors.size()) {
action.execute();
} else {
interceptors.get(index).intercept(this);
}
}
}
调用拦截器测试类
public class Test{
public static void main(String[] args) {
System.out.println("main before");
new ActionInvocation().invoke();
System.out.println("main before");
}
}
自定义拦截器:
自定义拦截器必须要实现Interceptor接口
public class MyInterceptor implements Interceptor {
public void destroy() {
}
public void init() {
}
public String intercept(ActionInvocation invocation) throws Exception {
long start = System.currentTimeMillis();
String r = invocation.invoke();
long end = System.currentTimeMillis();
System.out.println("action time = " + (end - start));
return r;
}
}
使用的时候需要在struts.xml文件中进行配置,而且拦截器是必须配置在包里面的.
<action name="test" class="com.bjsxt.action.TestAction">
<result>/test.jsp</result>
<interceptor-ref name="my"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>
因为每一个拦截器都是拦截的一个指定的请求,所以拦截器需要定义在具体Action里面
使用struts2 token拦截器:
这个拦截器主要是为了防止客户重复提交表单而加入的
使用token标签的时候,Struts2会建立一个GUID(全局唯一的字符串)放在session中,并且会成为一个hidden放在form中。
token拦截器会判断客户端form提交的token和session中保存的session是否equals。如果equals则执行Action。否则拦截器直接返回invaid.token结果,Action对应的方法也不会执行界面.
使用步骤:
1.在对应的需要防止客户重复提交表单的Action里面加入拦截器
<action name="user" class="com.bjsxt.action.UserAction">
<result>/addOK.jsp</result>
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="token"></interceptor-ref>
<!--当表单重复提价的时候指向的页面-->
<result name="invalid.token">/error.jsp</result>
</action>
<form action="test/input">
输入姓名:<input type="text" name="name"/>
<input type="submit" value="提交"/>
<s:token/>