Adding custom headers to Java HttpServletRequest

The javax.servlet.http.HttpServletRequest is an interface that does not have setter methods except for setCharacterEncoding() and setAttribute() methods that it inherits from its parent javax.servlet.ServletRequest interface. Otherwise, the HttpServletRequest type objects are read only.

There, often, are occasions where you may want to intercept the incoming HTTP request in an HttpServletFilter and add or modify its request headers. Below, I discuss a mechanism where I will show you how to add custom headers to an HttpServletRequest type object. The same mechanism can be applied to modify existing headers.

We use the decorator pattern to dynamically extend the functionality of HttpServletRequest type object and use the decorated object in place of the original object.

In the code below, I call the decorated HTTP servlet request class as the MutableHttpServletRequest that extends the HttpServletRequest implementation class called javax.servlet.http.HttpServletRequestWrapper and defines a constructor that accepts a HttpServletRequest type object.

The input HttpServletRequest type object is used as the backing request object. This is a standard decorator design pattern implementation that we employ here. Let me show you the code.

You would mostly be using this MutableHttpServletRequest class in the servlet filter to intercept incoming HTTP request to add some custom headers. Let me show you a sample usage.

Using the MutableHttpServletRequest class

 


 

1
Leave a Reply

avatar
300
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Zergham Recent comment authors
  Subscribe  
newest oldest
Notify of
Zergham
Guest
Zergham

putHeaders() will not work until getHeaders(String name) not overridden, as the extractRequestHeaders() from ServletUtil will alwalys call the Request.getHeaders().