背景
由于环境升级,需要重新设置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 MapgetHeadKeyAndValue(HttpServletRequest httpRequest) { Map header = new HashMap<>(); Enumeration headerNames = httpRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String nextElement = headerNames.nextElement(); header.put(nextElement, httpRequest.getHeader(nextElement)); } return header; }}@Slf4jpublic class HeaderMapRequestWrapper extends HttpServletRequestWrapper { /** * construct a wrapper for this request * * @param request */ public HeaderMapRequestWrapper(HttpServletRequest request) { super(request); } private Map 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); } @Override public 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 */ @Override public Enumeration getHeaderNames() { List names = Collections.list(super.getHeaderNames()); for (String name : headerMap.keySet()) { names.add(name); } return Collections.enumeration(names); } @Override public Enumeration getHeaders(String name) { log.info("getHeaders --->>>>>>{}",name); List 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的数组,而不是覆盖。