Struts2 Interceptor的原理

1.Struts2的interceptor是配置在xml文件中的:
interceptor: interceptor标签,必须包含名称和类名
interceptors: package标签的子标签,只用来包含interceptor-ref、
interceptor-stack,无其它作用
interceptor-ref: interceptor标签别名,可以指向interceptor,也可以指向
interceptor-stack
interceptor-stack: intercepor标签的集合,只包含interceptor-ref
default-interceptor-ref: action默认的interceptor集合
dtd描述代码:

<!ELEMENT interceptors (interceptor|interceptor-stack)+>

<!ELEMENT interceptor (param*)>
<!ATTLIST interceptor
name CDATA #REQUIRED
class CDATA #REQUIRED
>

<!ELEMENT interceptor-stack (interceptor-ref*)>
<!ATTLIST interceptor-stack
name CDATA #REQUIRED
>

<!ELEMENT interceptor-ref (param*)>
<!ATTLIST interceptor-ref
name CDATA #REQUIRED
>

<!ELEMENT default-interceptor-ref (#PCDATA)>
<!ATTLIST default-interceptor-ref
name CDATA #REQUIRED
>


2.Struts2的Interceptor是以责任链模式被调用的,包括ActionInvocation、Interceptor接口,以下为一个示意例子:


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

interface ActionInvocation{
public String invoke();
}

interface Interceptor{
public String intercept(ActionInvocation invocation);
}

class SampleActionInvocation implements ActionInvocation{

private Iterator interceptors = null;
private Action action = null;

void setInterceptors(List list){
interceptors = list.iterator();
}

void setAction(Action action){
this.action = action;
}

public String invoke(){
//do interceptor
if(interceptors.hasNext()){
Interceptor interceptor = (Interceptor)interceptors.next();
interceptor.intercept(this);
}else{
//do action
action.execute();
}
return null;
}
}

class SampleInterceptor implements Interceptor{
public String intercept(ActionInvocation invocation){
System.out.println(this.toString()+" before intercept");
invocation.invoke();
System.out.println(this.toString()+" after intercept");
return null;
}
}

class Action{
void execute(){
System.out.println(this.toString()+" excute ");
}
}

public class TestMain{
public static void main(String[] args){
SampleActionInvocation sai = new SampleActionInvocation();
List list = new ArrayList();
list.add(new SampleInterceptor());
list.add(new SampleInterceptor());
sai.setInterceptors(list);
sai.setAction(new Action());
sai.invoke();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值