使用HttpServletRequestWrapper重写Request请求参数
前言
改变请求参数的值,满足项目需求(通过过滤器过滤请求,增加用户信息进入到请求头)
public class HeaderHttpServletRequestWrapper extends HttpServletRequestWrapper {
private final Map<String, String> customHeaders;
public HeaderHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
this.customHeaders = new HashMap<>();
}
public void setHeader(String name, String value) {
this.customHeaders.put(name, value);
}
@Override
public String getHeader(String name) {
String headerValue = customHeaders.get(name);
if (null != headerValue) {
return headerValue;
}
return ((HttpServletRequest) getRequest()).getHeader(name);
}
@Override
public Enumeration<String> getHeaderNames() {
Set<String> set = new HashSet<>(customHeaders.keySet());
Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames();
while (e.hasMoreElements()) {
String n = e.nextElement();
set.add(n);
}
return Collections.enumeration(set);
}
@Override
public Enumeration<String> getHeaders(String name) {
List<String> values = Collections.list(super.getHeaders(name));
if (customHeaders.containsKey(name)) {
values = Collections.singletonList(customHeaders.get(name));
}
return Collections.enumeration(values);
}
}