在一些比较旧的代码中,或者是没有使用struts或spring的框架中,以及在一些无法或去request的类中,如果要想在不改变代码结果的情况下,扩展原有的功能,通常又不能直接修改当前的方法来扩展参数,这时就可以用到此方法。主要思想就是使用filter将每次的request保存到当前线程中,当filter使用完毕后移除request。
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>