Servlet Filter:如何从 servletRequest 中获取所有标头?

2022-08-31 12:12:25

这是我的样子WebFilter

@WebFilter("/rest/*")
public class AuthTokenValidatorFilter implements Filter {

    @Override
    public void init(final FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
        final Enumeration<String> attributeNames = servletRequest.getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            System.out.println("{attribute} " + servletRequest.getParameter(attributeNames.nextElement()));
        }

        final Enumeration<String> parameterNames = servletRequest.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            System.out.println("{parameter} " + servletRequest.getParameter(parameterNames.nextElement()));
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
    }
}

我试图在网上找到如何从请求中获取值的信息。HTTP headers

我没有找到任何东西,所以我试图枚举,但不知道任何事情,但我没有得到任何标题。servletRequest.getAttributeNames()servletRequest.getParameterNames()

问题
如何获取来自请求的所有标头?


答案 1

类型转换为(仅当 是 时)。ServletRequestHttpServletRequestServletRequest requestinstanceofHttpServletRequest

然后你可以使用和方法。HttpServletRequest.getHeader()HttpServletRequest.getHeaderNames()

像这样:

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    Enumeration<String> headerNames = httpRequest.getHeaderNames();

    if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                    System.out.println("Header: " + httpRequest.getHeader(headerNames.nextElement()));
            }
    }

    //doFilter
    chain.doFilter(httpRequest, response);
}

答案 2

使用 Java 8+,您可以使用流来收集请求标头:

HttpServletRequest httpRequest = (HttpServletRequest) request;

Map<String, String> headers = Collections.list(httpRequest.getHeaderNames())
    .stream()
    .collect(Collectors.toMap(h -> h, httpRequest::getHeader));

更新

@Matthias提醒我,标头可以有多个值:

Map<String, List<String>>

Map<String, List<String>> headersMap = Collections.list(httpRequest.getHeaderNames())    
    .stream()
    .collect(Collectors.toMap(
        Function.identity(), 
        h -> Collections.list(httpRequest.getHeaders(h))
    ));

org.springframework.http.HttpHeaders

HttpHeaders httpHeaders = Collections.list(httpRequest.getHeaderNames())
    .stream()
    .collect(Collectors.toMap(
        Function.identity(),
        h -> Collections.list(httpRequest.getHeaders(h)),
        (oldValue, newValue) -> newValue,
        HttpHeaders::new
    ));

https://gist.github.com/Cepr0/fd5d9459f17da13b29126cf313328fe3


推荐