1. 程式人生 > >struts2.0 Interceptor Configuration(攔截器配置)

struts2.0 Interceptor Configuration(攔截器配置)

  
  • 多個攔截器可以組成一個攔截器堆疊。每個攔截器命名為一。
  • 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>
攔截器和攔截器堆疊可以混合使用。但按順序執行。也可以設一個預設的如: <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>
  • 另外也可以把
<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(); } } }