以下是我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()
上进行枚举而不知道任何内容,但我没有得到任何标题。
问题
如何从请求中获取所有标题?
答案 0 :(得分:69)
Typecast ServletRequest
进入HttpServletRequest
(仅当ServletRequest request
为instanceof
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;
}));