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描述代码:
2.Struts2的Interceptor是以责任链模式被调用的,包括ActionInvocation、Interceptor接口,以下为一个示意例子:
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();
}
}