日期:2014-05-19 浏览次数:20773 次
package test;
import java.io.IOException;
import java.util.Enumeration;
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 TestFilter implements Filter{
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain fc) throws IOException, ServletException {
HttpServletRequest oldRequest = (HttpServletRequest) request;
// 打印原始数据
System.out.println("OLD REQUEST HEADER:");
Enumeration enumeration = oldRequest.getHeaderNames();
while(enumeration.hasMoreElements()) {
String name = (String) enumeration.nextElement();
System.out.println(name + "=" + oldRequest.getHeader(name));
}
// 包装新的客户化Request
ChangedRequest newRequest = new ChangedRequest(oldRequest);
// 添加新的HEADER
newRequest.addHeader("TestMyHeader", "This is a test");
fc.doFilter(newRequest, response);
}
public void init(FilterConfig arg0) throws ServletException {
}
}
package test;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* 用于包装REQUEST
* @author ALLEN
*
*/
public class ChangedRequest extends HttpServletRequestWrapper implements Enumeration<String>{
private Map<String,String> headerMap;
public ChangedRequest(HttpServletRequest request) {
super(request);
// 提取原本的HEADER内容
Enumeration enumeration = request.getHeaderNames();
headerMap = new HashMap<String, String>();
while(enumeration.hasMoreElements()) {
String name = (String) enumeration.nextElement();
headerMap.put(name, request.getHeader(name));
}
}
public Map<String, String> getHeaderMap() {
return headerMap;
}
public void setHeaderMap(Map<String, String> headerMap) {
this.headerMap =