我现在有一个需求,就是在jsp调到servlet之前,用filter进行拦截,然后在request的header中追加一项内容。
现在的进度:可以使用filter在对应的位置进行拦截,但是知道如何在header中追加内容。
需求是硬性的,必须在header中追加内容。
从网上查到可以利用filter对request头进行修改。
请问有人做过类似的机能嘛?跪等!!!!
------最佳解决方案--------------------
可以在Filter对Request做包装
上代码:
Filter部分
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 {
}
}
Request包装类:
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 = headerMap;
}
public void addHeader(String name,String value) {
headerMap.put(name, value);
}
/**
* 从自己的MAP中返回HEADER内容
* 这里只实现了getHeader,可以根据需要重写这2个函数
*/
@Override
public String getHeader(String name) {
return headerMap.get(name);