spring 如何在过滤器中添加请求头并在控制器中获取该头

vhipe2zx  于 12个月前  发布在  Spring
关注(0)|答案(3)|浏览(124)

我正在使用以下 Package 器来添加标题,它在请求中添加标题

final class MutableHttpServletRequest extends HttpServletRequestWrapper {
    // holds custom header and value mapping
    private final Map<String, String> customHeaders;

    public MutableHttpServletRequest(HttpServletRequest request){
        super(request);
        this.customHeaders = new HashMap<String, String>();
    }

    public void putHeader(String name, String value){
        this.customHeaders.put(name, value);
    }

    public String getHeader(String name) {
        // check the custom headers first
        String headerValue = customHeaders.get(name);

        if (headerValue != null){
            return headerValue;
        }
        // else return from into the original wrapped object
        return ((HttpServletRequest) getRequest()).getHeader(name);
    }

    public Enumeration<String> getHeaderNames() {
        // create a set of the custom header names
        Set<String> set = new HashSet<String>(customHeaders.keySet());

        // now add the headers from the wrapped request object
        @SuppressWarnings("unchecked")
        Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames();
        while (e.hasMoreElements()) {
            // add the names of the request headers into the list
            String n = e.nextElement();
            set.add(n);
        }

        // create an enumeration from the set and return
        return Collections.enumeration(set);
    }
}

字符串
与过滤器

@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(req);
    ...
    mutableRequest.putHeader("x-user-id", "1");
    chain.doFilter(mutableRequest, response);
}


但我不能在contoller它给空的标题,所以任何人请告诉我如何设置过滤器和访问控制器中的标题。

@GetMapping("/api1/temp1")
        private ResponseEntity<Object>  temp1(@RequestHeader HttpHeaders headers, @RequestHeader(value="x-user-id",required=false) String userId){
            System.out.println(userId));
            return new ResponseEntity<Object>("temp1 method", HttpStatus.OK);
        }

lkaoscv7

lkaoscv71#

当你向控制器发出请求时,第一个OPTIONS请求被发送,在这个请求中过滤器将找不到你设置的值。首先跳过选项请求,然后再试。

@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;

        if(!"OPTIONS".equalsIgnoreCase(request.getMethod())) {
    MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(req);
    ...
    mutableRequest.putHeader("x-user-id", "1");
    chain.doFilter(mutableRequest, response);
        }
}

字符串

bqjvbblv

bqjvbblv2#

在MutableHttpServletRequest类中调用getHeaders()以使用@RequestHeader获取值。

// MutableHttpServletRequest class
...
@Override
public Enumeration<String> getHeaders(String name) {
    Set<String> set = new HashSet();
    if (customHeaders.keySet().contains(name)) {
        set.add(getHeader(name));
    }
    @SuppressWarnings("unchecked")
    Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaders(name);
    while (e.hasMoreElements()) {
        String n = e.nextElement();
        set.add(n);
    }
    return Collections.enumeration(set);
}
...

字符串
此页面为您提供帮助https://neunggu.tistory.com/50

vfh0ocws

vfh0ocws3#

您需要重写HttpServletRequestWrapper#getHeaders(String name)方法并返回customHeader值以及其他头值。

public class MoreHeadersHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private final Map<String, String> headers;

    public MoreHeadersHttpServletRequestWrapper(
        HttpServletRequest request, Map<String, String> headers) {
      super(request);
      this.headers = Map.copyOf(headers);
    }

    @Override
    public String getHeader(String name) {
      return headers.getOrDefault(name, super.getHeader(name));
    }

    @Override
    public Enumeration<String> getHeaders(String name) {
      Set<String> extended = new HashSet<>();
      Optional.ofNullable(headers.get(name)).ifPresent(extended::add);
      Enumeration<String> headers = super.getHeaders(name);
      while (headers.hasMoreElements()) {
        String value = headers.nextElement();
        extended.add(value);
      }
      return Collections.enumeration(extended);
    }

    @Override
    public Enumeration<String> getHeaderNames() {
      Set<String> extended = new HashSet<>(headers.keySet());
      Enumeration<String> headerNames = super.getHeaderNames();
      while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        extended.add(headerName);
      }
      return Collections.enumeration(extended);
    }
  }

字符串

相关问题