您需要创建一个 FakeRequest 来解决它
FakeHeadersRequest
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class FakeHeadersRequest extends HttpServletRequestWrapper {
private Map<String, List<String>> headers = new HashMap<String, List<String>>();
public FakeHeadersRequest(HttpServletRequest request) {
super(request);
}
@Override
public String getHeader(String name) {
if (headers.containsKey(name)) {
return headers.get(name).get(0);
}
return super.getHeader(name);
}
public void addHeader(String header, String value) {
List<String> list = headers.get(header);
if (list == null) {
list = new ArrayList<String>();
headers.put(header, list);
}
list.add(value);
}
public void setHeader(String header, String value) {
List<String> list = new ArrayList<String>();
headers.put(header, list);
list.add(value);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public Enumeration getHeaderNames() {
List<String> list = new ArrayList<String>();
HttpServletRequest request = (HttpServletRequest) getRequest();
Enumeration<String> e = request.getHeaderNames();
while (e.hasMoreElements()) {
list.add(e.nextElement());
}
list.addAll(headers.keySet());
return Collections.enumeration(list);
}
}
FakeHeaderFilter
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;
public class FakeHeaderFilter implements Filter {
public void init(FilterConfig filterConfig) {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
boolean condition = false;
if (condition && request instanceof HttpServletRequest) {
FakeHeadersRequest req = new FakeHeadersRequest(
(HttpServletRequest) request);
req.setHeader("new-header", "some-value");
chain.doFilter(req, response);
} else {
chain.doFilter(request, response);
}
}
public void destroy() {
}
}
也参考这个