背景
由于环境升级,需要重新设置header中的 一个值,暂设定为 org . http 请求时加入在header中加入org,但在filter中,会通过验证,生成新的org,需要覆盖原来header中的org.
修改 filter 。代码是在网上找的一部分,根据自己的需要进行调整了。
@Component
@Slf4j
@WebFilter(urlPatterns = { "/" }, filterName = "authorFilter")
public class DemoFilter implements Filter {@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,FilterChain filterChain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) servletRequest;req.setAttribute("hdd","tttt");HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(req);requestWrapper.addHeader("realm","test");log.info("header-->{}",getHeadKeyAndValue(req));filterChain.doFilter(requestWrapper, servletResponse);}private Map<String, String> getHeadKeyAndValue(HttpServletRequest httpRequest) {Map<String, String> header = new HashMap<>();Enumeration<String> headerNames = httpRequest.getHeaderNames();while (headerNames.hasMoreElements()) {String nextElement = headerNames.nextElement();header.put(nextElement, httpRequest.getHeader(nextElement));}return header;}
}@Slf4j
public class HeaderMapRequestWrapper extends HttpServletRequestWrapper {/*** construct a wrapper for this request** @param request*/public HeaderMapRequestWrapper(HttpServletRequest request) {super(request);}private Map<String, String> headerMap = new HashMap<>();/*** add a header with given name and value** @param name* @param value*/public void addHeader(String name, String value) {headerMap.put(name, value);}@Overridepublic String getHeader(String name) {log.info("getHeader --->{}",name);String headerValue = super.getHeader(name);if (headerMap.containsKey(name)) {headerValue = headerMap.get(name);}return headerValue;}/*** get the Header names*/@Overridepublic Enumeration<String> getHeaderNames() {List<String> names = Collections.list(super.getHeaderNames());for (String name : headerMap.keySet()) {names.add(name);}return Collections.enumeration(names);}@Overridepublic Enumeration<String> getHeaders(String name) {log.info("getHeaders --->>>>>>{}",name);List<String> values = Collections.list(super.getHeaders(name));log.info("getHeaders --->>>>>>{}",values);if (headerMap.containsKey(name)) {log.info("getHeaders --->{}",headerMap.get(name));values = Arrays.asList(headerMap.get(name));}return Collections.enumeration(values);}
}
经过测试,在header解析时,是通过getHeaders方法,这个地方原来的时候是通过,values直接添加新的header,组成了一个 header的数组,而不是覆盖。