自已实现类似Spring的在任意代码中获取Request的功能

J2EE 码拜 10年前 (2015-07-18) 1183次浏览

1、主要步骤
1)定义一个ContextFilter
2)定义一个ContextHolder容器类,存放Request类
3)在Web.xml中配置ContextFilter

2、ContextFilter类

package com.joshho.context;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class ContextFilter implements Filter{

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws ServletException, IOException {

		saveRequest((HttpServletRequest)req);

		chain.doFilter(req, resp);

		removeRequest();
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

	private void saveRequest(HttpServletRequest req) {
		ThreadLocal<HttpServletRequest> requestThreadLocal = new ThreadLocal<HttpServletRequest>();
		requestThreadLocal.set((HttpServletRequest)req);
		Map<Thread, ThreadLocal<HttpServletRequest>> threadLocalMap =  ContextHolder.getThreadLocalMap();
		threadLocalMap.put(Thread.currentThread(), requestThreadLocal);
	}

	private void removeRequest() {
		Map<Thread, ThreadLocal<HttpServletRequest>> threadLocalMap = ContextHolder.getThreadLocalMap();
		threadLocalMap.remove(Thread.currentThread());
	}


}

3、ContextHolder类:


package com.joshho.context;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 自已实现的类似Spring的ContextHolder,在没有使用spring或struts的框架中,想要在一般的代码中获取request,可以使用此类
 * @author
 *
 */
public class ContextHolder {

	private static Map<Thread, ThreadLocal<HttpServletRequest>> requestThreadLocalMap = new HashMap<Thread, ThreadLocal<HttpServletRequest>>();

	public static HttpServletRequest getRequest() {
		return (HttpServletRequest) requestThreadLocalMap.get(Thread.currentThread()).get();
	}

	public static Map<Thread, ThreadLocal<HttpServletRequest>> getThreadLocalMap() {
		return requestThreadLocalMap;
	}

	public static void setThreadLocalMap(Map<Thread, ThreadLocal<HttpServletRequest>> threadLocalMap) {
		ContextHolder.requestThreadLocalMap = threadLocalMap;
	}


}

4、Web.xml配置

        <filter>
		<filter-name>contextFilter</filter-name>
		<filter-class>com.joshho.context.ContextFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>contextFilter</filter-name>
		<url-pattern>*.jsp</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>contextFilter</filter-name>
		<url-pattern>/xxx</url-pattern>
	</filter-mapping>

20分

#1

很好呀。很好呀。很好呀。

#2

回复1楼:

谢谢


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明自已实现类似Spring的在任意代码中获取Request的功能
喜欢 (0)
[1034331897@qq.com]
分享 (0)