- 多个拦截器可以组成一个拦截器堆栈。每个拦截器命名为一。
- Registering Interceptors
<interceptors>
<interceptor name="security" class="com.company.security.SecurityInterceptor"/>
<interceptor-stack name="secureStack">
<interceptor-ref name="security"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<interceptor name="security" class="com.company.security.SecurityInterceptor"/>
<interceptor-stack name="secureStack">
<interceptor-ref name="security"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
拦截器和拦截器堆栈可以混合使用。但按顺序执行。也可以设一个默认的如:
|
<default-interceptor-ref name="secureStack"/> |
- 每个Action也可以定义自己的拦截器:
A local Interceptor Stack
<action name="VelocityCounter" class="org.apache.struts2.example.counter.SimpleCounter">
<result name="success"> ... </result>
<interceptor-ref name="defaultComponentStack"/>
</action>
<result name="success"> ... </result>
<interceptor-ref name="defaultComponentStack"/>
</action>
- 另外也可以把
<package name="actionName" extends="struts-default">
<interceptors>
<interceptor name="userAccessInterceptor"
class="tool.UserAccessInterceptor">
</interceptor>
<interceptor-stack name="myInter">
<interceptor-ref name="userAccessInterceptor"></interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myInter"></default-interceptor-ref>
放到一个单独的文件,单独的包中,用的时候先导入文件在继承包名就可以了。
- 自定义拦截器的一般写法:
//Source file: F:/java/Oil/src/com/xj/tools/UserAccessInterceptor.java
package tool;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class UserAccessInterceptor extends AbstractInterceptor {
@Override
public void destroy() {
// TODO Auto-generated method stub
super.destroy();
}
@Override
public void init() {
// TODO Auto-generated method stub
super.init();
}
@Override
public String intercept(ActionInvocation arg0) throws Exception {
// TODO Auto-generated method stub
Map session = arg0.getInvocationContext().getSession();
String username = (String) session.get("username");
if ((username == null || username == ""))
return "input";
else {
return arg0.invoke();
}
}
}