<p> 先了解一下struts2官网是如何定义过滤器的:</p><p> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</p>
<span style="white-space:pre"> </span>//初始化参数作用
public void init(FilterConfig filterConfig) throws ServletException {}
<span style="white-space:pre"> </span>//一个空的回调方法
protected void postInit(Dispatcher dispatcher, FilterConfig filterConfig) {
}
<span style="white-space:pre"> </span>//过滤器的执行方法
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {}
<span style="white-space:pre"> </span>//释放资源
public void destroy() {}
那么 如果要做一个比较特殊 的东西进行过滤拦截,就可以采用继承于StrutsPrepareAndExecuteFilter 这个方法。
并重写其中 init() doFilter() 这两个方法了 来达到目的
配置web.xml
</pre><pre name="code" class="java">web.xml
<filter>
<filter-name>action2</filter-name>
<!--自己定义的过滤器 来实现特殊的业务需求-->
<filter-class>com.test.util.ReFilterDispacher</filter-class>
<init-param>
<param-name>config</param-name>
<param-value>struts-default.xml,struts-plugin.xml,struts/struts.xml,classpath*:struts/struts_*.xml</param-value>
</init-param>
</filter>
package com.test.util;
public class ReFilterDispacher extends StrutsPrepareAndExecuteFilter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
<span style="white-space:pre"> </span>//实现初始化的某些参数定义
ReInitOperations init = new ReInitOperations();
Dispatcher dispatcher = null;
try {
FilterHostConfig config = new FilterHostConfig(filterConfig);
<span style="white-space:pre"> </span>//初始化struts内部的log配置
init.initLogging(config);
<span style="white-space:pre"> </span>//可重写改变某配置信息
dispatcher = init.initDispatcher(config);
this.prepare = new PrepareOperations(dispatcher);
this.excludedPatterns = init.buildExcludedPatternsList(dispatcher);
postInit(dispatcher, filterConfig);
} finally {
if (dispatcher != null) {
dispatcher.cleanUpAfterInit();
}
init.cleanup();
}
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
// 过滤器的执行方法 可以改变http请求过来的参数进行拦截过滤或改变其值
super.doFilter(arg0, arg1, arg2);
}
}
至此 你就可以在此过滤器做一些自己想做的业务方面东西。
过滤器可影响到所有HTTP前台请求,并实现了,也让action脱离web容器。