Servlet过滤器:如何从servletRequest获取所有头文件?

时间:2014-08-11 15:44:19

标签: java java-ee servlets servlet-filters

以下是我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()上进行枚举而不知道任何内容,但我没有得到任何标题。

问题
如何从请求中获取所有标题?

3 个答案:

答案 0 :(得分:69)

Typecast ServletRequest进入HttpServletRequest(仅当ServletRequest requestinstanceof HttpServletRequest时)。

然后您可以使用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);
}

答案 1 :(得分:23)

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

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

答案 2 :(得分:0)

您应该考虑相同的HTTP标头可以使用不同的值多次出现:

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;
}));