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?
With Java 8 you can use a stream to collect request headers:
UPDATED
@Matthias reminded me of the possibility to have multiple values for one header:
Map<String, List<String>>
org.springframework.http.HttpHeaders
https://gist.github.com/Cepr0/fd5d9459f17da13b29126cf313328fe3
You should consider that the same HTTP header can occur multiple times with different values:
Typecast
ServletRequest
intoHttpServletRequest
(only ifServletRequest request
is aninstanceof
HttpServletRequest
).Then you can use
HttpServletRequest.getHeader()
andHttpServletRequest.getHeaderNames()
method.Something like this: