Struts.xml配置檔案
<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE strutsPUBLIC
"-//Apache Software Foundation//DTD StrutsConfiguration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- 開發模式 -->
<constant name="struts.devMode"value="true" />
<!-- spring管理struts -->
<constant name="struts.objectFactory"value="spring" />
<package name="struts-shop" extends="struts-default">
<interceptors>
<!-- 先定義攔截器自己寫的攔截器類 name随便寫 class為全限定名 -->
<interceptor name="filterInterceptor"class="com.bw.lanjieqi.FilterInterceptor"/>
<!-- 加到自己設定的攔截器棧裡邊去 -->
<interceptor-stack name="myStack">
<!-- name為上面interceptor标簽裡面定義的name-->
<interceptor-ref name="filterInterceptor">
<!--攔截器黑白名單 includeMethods為攔截的方法 excludeMethods不攔截這倆可以單獨存在 -->
<param name="includeMethods">toAdd</param>
<param name="excludeMethods">toUpdate</param>
<!--指定參數name的值 可以不寫不需要就不寫-->
<param name="name">FilterMethod</param>
</interceptor-ref>
<!-- 在自己配置的攔截器基礎上,必須有struts2預設的攔截器,不然出錯 -->
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 應用攔截器不寫攔截器不生效 -->
<default-interceptor-ref name="myStack"/>
</package>
<!-- 将其他的struts2的配置檔案加載到主配置檔案struts.xml裡 -->
<include file="struts-action.xml" />
</struts>
Struts-action.xml配置檔案
<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE strutsPUBLIC
"-//Apache Software Foundation//DTD StrutsConfiguration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- extends繼承struts.xml裡的攔截器的配置 -->
<package name="city"extends="struts-shop">
<action name="city_*"class="com.bw.action.CityAction" method="{1}">
<result name="list">/WEB-INF/view/list.jsp</result>
<result name="toAdd">/WEB-INF/view/add.jsp</result>
<result name="toUpdate">/WEB-INF/view/update.jsp</result>
<result name="success"type="redirect">city_list</result>
</action>
</package>
</struts>
FilterInterceptor
package com.bw.lanjieqi;
import java.util.Date;
import com.bw.action.CityAction;
import com.opensymphony.xwork2.ActionInvocation;
importcom.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
publicclass FilterInterceptor extends MethodFilterInterceptor{
//配置檔案中指定的參數可以不用
private String name;
public String getName() {
returnname;
}
publicvoid setName(Stringname) {
this.name = name;
}
@Override
protected StringdoIntercept(ActionInvocation invocation) throws Exception {
// TODO Auto-generated method stub
//擷取要攔截的action 如果不過過多的處理可以不寫
CityActionfa= (CityAction)invocation.getAction();
System.out.println(name+"攔截器在Action執行前攔截"+new Date());
String result=invocation.invoke();
System.out.println(name+"攔截器在Action執行後攔截"+new Date());
return result;
}
}