Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Servlet Filter: How to get all the headers from servletRequest?

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?

like image 725
daydreamer Avatar asked Aug 11 '14 15:08

daydreamer


People also ask

What is ServletRequest and ServletResponse?

ServletRequest and ServletResponse are two interfaces that serve as the backbone of servlet technology implementation. They belong to the javax. servlet package. Signature: public interface ServletRequest. Blueprint of an object to provide client request information to a servlet.


1 Answers

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); } 
like image 62
Buhake Sindi Avatar answered Oct 04 '22 11:10

Buhake Sindi