文档章节

将几个Filter整合成一个Filter

abcijkxyz
 abcijkxyz
发布于 2016/07/08 16:28
字数 533
阅读 4
收藏 0

 CAS-Client的客户端配置还是多Filter,这个对于接入系统比较繁琐,我试着将这几个Filter合并成一个。

 

FilterChainProxy :其职责是给web.xml使用,接受其他需要合并的Filter的参数,初始化其他Filter.

FilterInvocation:doFilter的参数的封装,取得路径信息等。

VirtualFilterChain:实现FilterChain,

代码如下:

FilterChainProxy

public class FilterChainProxy extends AbstractConfigurationFilter {

	Logger logger = Logger.getLogger(FilterChainProxy.class);

	private Filter[] filters;

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {

		for (int i = 0; i < filters.length; i++) {
			if (filters[i] != null) {
				if (logger.isDebugEnabled()) {
					logger.debug("Destroying Filter defined in ApplicationContext: '" + filters[i].toString() + "'");
				}

				filters[i].destroy();
			}
		}

	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		 FilterInvocation fi = new FilterInvocation(request, response, chain);
		
		if (filters.length == 0) {
			if (logger.isDebugEnabled()) {
				logger.debug(fi.getRequestUrl()+" has an empty filter list");
			}
			chain.doFilter(request, response);

			return;
		}
		
		VirtualFilterChain virtualFilterChain = new VirtualFilterChain(fi, filters);
		virtualFilterChain.doFilter(fi.getRequest(), fi.getResponse());

	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		filters = obtainAllDefinedFilters();

		for (int i = 0; i < filters.length; i++) {
			if (filters[i] != null) {
				if (logger.isDebugEnabled()) {
					logger.debug("Initializing Filter defined in ApplicationContext: '" + filters[i].toString() + "'");
				}
				filters[i].init(filterConfig);
			}
		}

	}
	/**
	 * 初始化单点登录需要的过滤器
	 * @return
	 */
	private Filter[] obtainAllDefinedFilters() {

		Set<Filter> list = new LinkedHashSet<Filter>();
		// SingleSignOutFilter
		list.add(new SingleSignOutFilter());
		// AuthenticationFilter
		list.add(new AuthenticationFilter());
		// Cas20ProxyReceivingTicketValidationFilter
		list.add(new Cas20ProxyReceivingTicketValidationFilter());
		// AssertionThreadLocalFilter
		list.add(new AssertionThreadLocalFilter());
		// HttpServletRequestWrapperFilter
		list.add(new HttpServletRequestWrapperFilter());

		return (Filter[]) list.toArray(new Filter[0]);
	}

VirtualFilterChain

private class VirtualFilterChain implements FilterChain {
		private FilterInvocation fi;
		private Filter[] additionalFilters;
		private int currentPosition = 0;

		public VirtualFilterChain(FilterInvocation filterInvocation, Filter[] additionalFilters) {
			  this.fi = filterInvocation;
	          this.additionalFilters = additionalFilters;
		}

		public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
			if (currentPosition == additionalFilters.length) {
				if (logger.isDebugEnabled()) {
					logger.debug(fi.getRequestUrl()
							+ " reached end of additional filter chain; proceeding with original chain");
				}

				fi.getChain().doFilter(request, response);
			} else {
				currentPosition++;

				if (logger.isDebugEnabled()) {
					logger.debug(fi.getRequestUrl() + " at position " + currentPosition + " of "
							+ additionalFilters.length + " in additional filter chain; firing Filter: '"
							+ additionalFilters[currentPosition - 1] + "'");
				}

				additionalFilters[currentPosition - 1].doFilter(request, response, this);
			}
		}

	}


FilterInvocation

public class FilterInvocation {
	private FilterChain chain;
	private ServletRequest request;
	private ServletResponse response;

	public FilterInvocation(ServletRequest request, ServletResponse response, FilterChain chain) {
		if ((request == null) || (response == null) || (chain == null)) {
			throw new IllegalArgumentException("Cannot pass null values to constructor");
		}

		if (!(request instanceof HttpServletRequest)) {
			throw new IllegalArgumentException("Can only process HttpServletRequest");
		}

		if (!(response instanceof HttpServletResponse)) {
			throw new IllegalArgumentException("Can only process HttpServletResponse");
		}

		this.request = request;
		this.response = response;
		this.chain = chain;
	}

	public FilterChain getChain() {
		return chain;
	}

	/**
	 * Indicates the URL that the user agent used for this request.<P>The returned URL does <b>not</b> reflect
	 * the port number determined from a {@link org.acegisecurity.util.PortResolver}.</p>
	 *
	 * @return the full URL of this request
	 */
	public String getFullRequestUrl() {
		return UrlUtils.getFullRequestUrl(this);
	}

	public HttpServletRequest getHttpRequest() {
		return (HttpServletRequest) request;
	}

	public HttpServletResponse getHttpResponse() {
		return (HttpServletResponse) response;
	}

	public ServletRequest getRequest() {
		return request;
	}

	/**
	 * Obtains the web application-specific fragment of the URL.
	 *
	 * @return the URL, excluding any server name, context path or servlet path
	 */
	public String getRequestUrl() {
		return UrlUtils.getRequestUrl(this);
	}

	public ServletResponse getResponse() {
		return response;
	}

	public String toString() {
		return "FilterInvocation: URL: " + getRequestUrl();
	}
}



 

本文转载自:http://blog.csdn.net/yuwenruli/article/details/6829646

共有 人打赏支持
abcijkxyz
粉丝 64
博文 6196
码字总数 1876
作品 0
深圳
项目经理
对chain.doFilter(request,response)的理解

他的作用是将请求转发给过滤器链上下一个对象。这里的“下”指的是哪里 ? 指的是下一个filter,如果没有filter那就是你请求的资源。 一般filter都是一个链,web.xml 里面配置了几个就有几个。...

simplesns
2010/12/08
26.7K
5
springboot的shiro配置之过滤器

springboot整合shiro的文章到处都是。包括springboot的官网都有相应的例子。但是这块有个注意点,需要那些从springmvc迁到springboot的朋友注意下。这个问题困扰我了两三天,今天分享出来让后...

hyssop
2016/11/21
97
0
Spring Session关键类源码分析

要想使用spring session,还需要创建名为springSessionRepositoryFilter的SessionRepositoryFilter类。该类实现了Sevlet Filter接口,当请求穿越sevlet filter链时应该首先经过springSession...

芥末无疆
02/17
0
0
设计模式——责任链模式

使用场景: 现在有如下字符 :) English < > ,现在想把其转换为 ^V^ 英文 [],并且根据要求对 :) English < > 这三类字符分别转换 解决办法: (1)if else进行处理,低级的办法,不多说。 ...

wjk_snail
2015/09/15
61
0
SpringMVC集成Spring-Session进行分布式管理

项目使用的是SpringMVC+hibernate,听从老大的意见使用Spring-Session进行处理session,用redis托管Session。下面正式记录下处理方法。 1.如果项目之前没有整合过spring-data-redis的话,这...

圣杰是也
2015/12/28
2.7K
10

没有更多内容

加载失败,请刷新页面

加载更多

Python深体验,常见的数据处理方式(必须要懂的)

1.缺失值处理 - 拉格朗日插值法 input_file数据文件内容(存在部分缺失值): from scipy.interpolate import lagrangeimport pandas as pdimport numpy as npinput_file = './dat...

无也Python
23分钟前
2
0
Spring MVC注解故障追踪记

Spring MVC是美团点评很多团队使用的Web框架。在基于Spring MVC的项目里,注解的使用几乎遍布在项目中的各个模块,有Java提供的注解,如:@Override、@Deprecated等;也有Spring提供的注解,...

Skqing
25分钟前
4
0
区块链入门教程以太坊源码分析cmd包分析

  兄弟连区块链入门教程以太坊源码分析cmd包分析。 ### cmd包概述 * geth 主要Ethereum CLI客户端。它是Ethereum网络(eth主网,测试网络或私有网)的入口点,使用此命令可以使节点作为ful...

兄弟连区块链入门教程
27分钟前
1
0
@Autowired 报红线

代码可正常跑,不过红线看着有点难受,解决方案 使用@Autowired(required=false) 或者@Resource. 这两者区别网上一大堆

斩神魂
32分钟前
1
0
DataTable中检索信息 (C#)

C#_从DataTable中检索信息 存在于内存中的虚拟表DataTable,绑定在数据显示控件后,如果想在再检索其中某些信息,可以利用DataTable.Select方法进行检索,避免了重复的读取数据库。Select方法...

CS-CS01
40分钟前
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部