Adding HTTP Headers To Requests in Filters and Servlets

Aim
The aim of this tutorial is to demonstrate how you can add Headers to the ServletRequest and HttpServletRequest objects in either servlets or filters. This requires subclassing the HttpServletRequestWrapper class.

Assumptions
This article assumes that you can compile, deploy and test the filter/servlet.  For an example that demonstrates compiling and deploying a filter please go to Complete Java Filter Example. To create a JSP page that will display headers please have a look at JSP Page That Displays All Headers and Parameters.


  1. First let us have a look at subclassing the HttpServletRequestWrapper class. As you can see we have overridden getHeaderNames and getHeader to include our custom headers. These custom header are added through the addHeader function which is a new function. Our custom headers are stored in a hashmap.
     1. package myfilter;
     2. 
     3. import javax.servlet.http.HttpServletRequest;
     4. import javax.servlet.http.HttpServletRequestWrapper;
     5. import java.util.*;
     6. 
     7. public class MyServletRequestWrapper extends HttpServletRequestWrapper{
     8. 
     9.     private Map headerMap;
    10.     
    11.     public void addHeader(String name, String value){
    12.         headerMap.put(name, new String(value));
    13.     }
    14.     
    15.     public MyServletRequestWrapper(HttpServletRequest request){
    16.         super(request);
    17.         headerMap = new HashMap();
    18.     }
    19. 
    20.     public Enumeration getHeaderNames(){
    21.         
    22.         HttpServletRequest request = (HttpServletRequest)getRequest();
    23.         
    24.         List list = new ArrayList();
    25.         
    26.         for( Enumeration e = request.getHeaderNames() ; e.hasMoreElements() ;)
    27.             list.add(e.nextElement().toString());
    28.         
    29.         for( Iterator i = headerMap.keySet().iterator() ; i.hasNext() ;){
    30.             list.add(i.next());
    31.         }
    32.         
    33.         return Collections.enumeration(list);
    34.     }
    35.     
    36.     public String getHeader(String name){
    37.         Object value;
    38.         if((value = headerMap.get(""+name)) != null)
    39.             return value.toString();
    40.         else
    41.             return ((HttpServletRequest)getRequest()).getHeader(name);
    42.         
    43.     }
    44. }
    Hide line numbers

  2. Now let's have a look at a filter that will use this wrapper to add some custom headers. You can observe on line 31 how we use the wrapper to wrap the HttpServletRequest.
     1. package myfilter;
     2. 
     3. import java.io.IOException;
     4. import javax.servlet.*;
     5. import javax.servlet.http.HttpServletRequest;
     6. import javax.servlet.http.HttpServletResponse;
     7. import javax.servlet.http.HttpServletResponseWrapper;
     8. import javax.servlet.http.HttpSession;
     9. 
    10. import java.util.logging.*;
    11. 
    12. 
    13. public class MyFilter implements javax.servlet.Filter {
    14.     private ServletContext servletContext;
    15.     private Logger log;
    16.     
    17.     public MyFilter(){
    18.         super();
    19.     }
    20.     
    21.     public void init(FilterConfig filterConfig) throws ServletException {
    22.         servletContext = filterConfig.getServletContext();
    23.         log = Logger.getLogger(MyFilter.class.getName());
    24.     }
    25. 
    26.     public void doFilter(   ServletRequest req, 
    27.                             ServletResponse res, 
    28.                             FilterChain filterChain)
    29.         throws IOException, ServletException {
    30. 
    31.         MyServletRequestWrapper httpReq    = new MyServletRequestWrapper((HttpServletRequest)req);
    32.         HttpServletResponse    httpRes   = (HttpServletResponse)res;
    33.         
    34.         HttpSession session = httpReq.getSession();
    35. 
    36.         httpReq.addHeader("MY-HEADER-X1", "header 1");
    37.         httpReq.addHeader("MY-HEADER-X2", "header 2");
    38. 
    39.         filterChain.doFilter(httpReq, httpRes);
    40.             
    41.     }
    42. 
    43.     public void destroy(){
    44.     }
    45. 
    46. }
    Hide line numbers

9 comments:

Nathan Ferry said...

AWE-SOME.

tea said...

Way HTTP Compression Servlet Filter 2Way compression filter is a Servlet filter that compresses and decompresses both HTTP requests and HTTP responses using gzip. It was originally written to compress SOAP messages, but it can be used for any Web appl.

Muhammad said...

Using this filter (add request headers), I can add custom header in request and can also get Header name and value in JSP. However the header name and its value is not populated in web browser. (I used firebug in firefox to display request header). Am I doing something wrong. Thanks

righteous said...

Hi Muhammad,

There are headers that go from the client to the server and there are headers that go from the server back to the client.

In this example the header is added to the Request, this means that you jsp/application server will see it.

To send headers to the client you have to add headers to the Response. These are the headers that will appear on firefox

Luis said...

Great post!!!

Thank you very much,

Luis

Luis said...

Hi,

I am trying to use this implementation with a a servlet that redirect to a jsp through response.sendRedirect(). What I would like is to print the added header in the jsp.

Now I am able to get the added header just before the sendRedirect() but after I lose it.

Thanks in advance,

Luis

righteous said...

Luis,
The header will reach the servlet, but when the servlet sends a sendRedirect(), that request is bounced off the browser - so any heads you set will be lost.

I suggest you try forwarding the request from your servlet to the jsp using RequestDispatcher

Amit said...

Hi,

Wonderful Article!
I am trying to use the above example in WebSphere App Server 7, however getting the following error where I typecast the ServletRequest to custom wrapper.

java.lang.ClassCastException: com.ibm.ws.webcontainer.srt.SRTServletRequest incompatible with com.util.CustomServletRequestWrapper

I also tried to use the same code in JSP, there also it is using the object of com.ibm.ws.webcontainer.srt.SRTServletRequest, please advise how I can resolve this problem.

Thanks
Amit

Naviya Nair said...

Very interesting and good Explanation
ASP NET Training
ASP NET Training
ASP NET Online Training
C-Sharp Training
Dot Net Training in Chennai
Online .Net Training


MVC Training
WCF Training
Web-API Training
LINQ Training
Entity Framework
Training

Dot Net Interview Questions