Struts2拦截器实现原理

拦截器的实现主要靠得是一个拦截器链,另外的一个是拦截器的调用的类,它的目的就是在真正执行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>

2.在对应的表单里面加上<s:token/>标记

<form action="test/input">
  输入姓名:<input type="text" name="name"/>
  <input type="submit" value="提交"/>
  <s:token/>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值