Servlet Filter: How to get all the headers from se

2020-02-19 02:50发布

Here is how my WebFilter looks like

@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() {
    }
}

I tried to find out online as to how to get values for HTTP headers coming from request.

I did not find anything, so I tried to enumerate on servletRequest.getAttributeNames() and servletRequest.getParameterNames() without knowing anything, but I do not get any headers.

Question
How can I get all the headers coming from the request?

3条回答
家丑人穷心不美
2楼-- · 2020-02-19 03:22

With Java 8 you can use a stream to collect request headers:

HttpServletRequest httpRequest = (HttpServletRequest) request;

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

UPDATED

@Matthias reminded me of the possibility to have multiple values for one header:

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(r.getHeaders(h)),
        (oldValue, newValue) -> newValue,
        HttpHeaders::new
    ));

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

查看更多
来,给爷笑一个
3楼-- · 2020-02-19 03:25

You should consider that the same HTTP header can occur multiple times with different values:

Map<String, Serializable> headers = Collections.list(request.getHeaderNames()).stream().collect(Collectors.toMap(h -> h, h -> {
    ArrayList<String> headerValues = Collections.list(request.getHeaders(h));
    return headerValues.size() == 1 ? headerValues.get(0) : headerValues;
}));
查看更多
手持菜刀,她持情操
4楼-- · 2020-02-19 03:29

Typecast ServletRequest into HttpServletRequest (only if ServletRequest request is an instanceof HttpServletRequest).

Then you can use HttpServletRequest.getHeader() and HttpServletRequest.getHeaderNames() method.

Something like this:

@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);
}
查看更多
登录 后发表回答