文档章节

将几个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
粉丝 60
博文 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
设计模式——责任链模式

使用场景: 现在有如下字符 :) 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
Simpleframework整合Struts2的简化实现

Simpleframework整合Struts2的简化实现 概念 Simpleframework整合Struts2配置文档,这里simple 整合Struts2,只是对Struts2做了业务功能的补充,在整合好的应用中,simple 提供内置的组件,比...

simplesns
2010/12/07
200
1

没有更多内容

加载失败,请刷新页面

加载更多

下一页

spring 容器实现对bean的管理(注解方式解析,源码阅读)

因为最近在研究学习spring boot,所以这里想详细学习回顾了一下spring 容器对bean的一些管理方式和部分源码学习。 首先初始类AnnotationConfigApplicationContext,简单源码查看,支持两个参...

小海bug
11分钟前
0
0
数据结构:二分查找 java

二分查找的前提是有序存储,利用顺序存储和元素排序 /** * 二分查找,查找成功,返回下标记 * @param values * @param begin * @param end * @param key * @param <T> * @ret...

京一
28分钟前
0
0
@SpringBootApplication 注解

@SpringBootApplication注解是一个组合注解,包含以下注解 @Target(ElementType.TYPE) 注解的作用目标 @Retention(RetentionPolicy.RUNTIME) Reteniton的作用是定义被它所注解的注解保留多久,...

java.刘
41分钟前
0
0
sentinel自定义DataSource实战

序 本文主要研究一下如何自定义sentinel的DataSource,这里以jdbc为例。 maven <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-sen......

go4it
57分钟前
1
0
xgboost/gbdt在调参时为什么树的深度很少就能达到很高的精度?

问题: 用xgboost/gbdt在在调参的时候把树的最大深度调成6就有很高的精度了。但是用DecisionTree/RandomForest的时候需要把树的深度调到15或更高。用RandomForest所需要的树的深度和Decisio...

tantexian
58分钟前
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部