Struts2整合自定義攔截器
阿新 • • 發佈:2019-01-12
1. web.xml配置
<!-- 自定義攔截器進行文字過濾攔截 --> <filter> <filter-name>interceptor</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>interceptor</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
注意: FilterDispathcer (org.apache.struts2.dispatcher.FilterDispatcher) 在早期的Struts2開發中使用,從Struts 2.1.3開始,它已不推薦使用。
如果你使用的Struts的版本 >= 2.1.3,推薦升級到新的Filter-StrutsPrepareAndExecuteFilter (org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter)。
2. 定義攔截器類
package com.centralsoft.framework.interceptor; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; import com.ArticleAction; // 專案定義的action類 public class CharacterFilterInterceptor extends AbstractInterceptor { @Override public String intercept(ActionInvocation ai) throws Exception { // TODO Auto-generated method stub //獲取action例項 Object obj = ai.getAction(); if(obj!=null){ // TODO 確定你需要處理的Action if(obj instanceof ArticleAction){ // ArticleAction action = (ArticleAction)obj; // TODO 這裡就可以開始處理你需要處理的物件 return ai.invoke(); // 將控制轉移給後續的攔截器,直到動作 }else{ return Action.LOGIN; // 停止後續的執行,並且決定哪個結果被呈現(引入的struts.xml對應,見第3條) } }else{ return Action.LOGIN; } } }
3. 配置struts.xml
<struts> <package name="cms" namespace="/cms" extends="struts-default"> <!-- 定義攔截器 --> <interceptors> <interceptor name="replace" class="com.CharacterFilterInterceptor"/> </interceptors> <action name="articleSaveImage" method="saveImage" class="ArticleAction"> <result name="login">/login.jsp</result> <result name="success">/success.jsp</result> <result name="error">/error.jsp</result> <!-- 使用攔截器 defaultStack是必要的--> <interceptor-ref name="defaultStack"/> <interceptor-ref name="replace"/> </action> </struts>
另一種方式:
<struts>
<package name="cms" namespace="/cms" extends="struts-default">
<!-- 定義攔截器 -->
<interceptors>
<interceptor name="replace"
class="com.CharacterFilterInterceptor"/>
<interceptor-stack name="myStack">
<interceptor-ref name="replace"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<action name="articleSaveImage" method="saveImage" class="ArticleAction">
<result name="login">/login.jsp</result>
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
<!-- 使用攔截器 -->
<interceptor-ref name="myStack"/>
</action>
</struts>