//把request、response传入
import java.io.IOException;
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;
import javax.servlet.http.HttpServletResponse;
public class RequestFilter implements Filter {
//创建线程
public static ThreadLocal<HttpServletRequest> threadLocalRequest = newThreadLocal<HttpServletRequest>();
public static ThreadLocal<HttpServletResponse> threadLocalResponse = newThreadLocal<HttpServletResponse>();
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
threadLocalRequest.set((HttpServletRequest) arg0);
threadLocalResponse.set((HttpServletResponse) arg1);
arg2.doFilter(arg0, arg1);
}
public void destroy() {}
public void init(FilterConfig arg0) throws ServletException {}
}
在类RequestFilter中写好代码后在WEB-INF目录下的web.xml文件中注册此类,
<filter>
<filter-name>RequestFilter</filter-name>
<filter-class>架包名.RequestFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>RequestFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>RequestFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
转自:http://www.zhangriguang.cn/blog/20121010123838.html