1. 步骤

  1. 新增一个继承自 HttpServletRequestWrapper 的 HeaderMapRequestWrapper 类
  2. 在 Filter 中使用自定义的 HeaderMapRequestWrapper 类对请求进行包装并新增或修改 header 参数即可

2. 代码示例

1. HeaderMapRequestWrapper 类
package com.example.demo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

/**
 * @author hsuyeung
 * @date 2022/12/23
 */
public class HeaderMapRequestWrapper extends HttpServletRequestWrapper {
    private final HashMap<String, String> headerMap = new HashMap<>();

    public HeaderMapRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    public void addHeader(String name, String value) {
        headerMap.put(name, value);
    }

    @Override
    public String getHeader(String name) {
        return headerMap.containsKey(name)
                ? headerMap.get(name)
                : super.getHeader(name);
    }


    @Override
    public Enumeration<String> getHeaderNames() {
        List<String> names = Collections.list(super.getHeaderNames());
        names.addAll(headerMap.keySet());
        return Collections.enumeration(names);
    }

    @Override
    public Enumeration<String> getHeaders(String name) {
        List<String> values = Collections.list(super.getHeaders(name));
        if (headerMap.containsKey(name)) {
            values.add(headerMap.get(name));
        }
        return Collections.enumeration(values);
    }
}

2. 新增 Filter
package com.example.demo;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author hsuyeung
 * @date 2022/12/23
 */
@Component
public class AddHeaderFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(req);
        // 新增一个叫 test 的 header 参数,如果已经存在则会被替换
        requestWrapper.addHeader("test", "test header value");
        filterChain.doFilter(requestWrapper, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}

3. 测试结果

测试接口
package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author hsuyeung
 * @date 2022/12/23
 */
@RestController
@RequestMapping("/api/demo")
public class DemoApi {

    /**
     * 获取请求中指定名字的 header 值
     *
     * @param headerName header 名字
     * @param request    请求
     * @return header 值
     */
    @GetMapping("/header/{headerName}")
    public String getCustomHeader(@PathVariable("headerName") String headerName,
                                  HttpServletRequest request) {
        return request.getHeader(headerName);
    }
}

请求结果
GET http://localhost:8080/api/demo/header/test

HTTP/1.1 200 
Content-Type: text/plain;charset=UTF-8
Content-Length: 17
Date: Fri, 23 Dec 2022 06:54:55 GMT
Keep-Alive: timeout=60
Connection: keep-alive

test header value

可以看见返回的响应结果里有了我们自定义的 header 参数。