struts2 自定义过 滤器

<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容器。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值