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



0 0 vote
Article Rating
Notify of
Oldest Most Voted
Inline Feedbacks
View all comments
1 year ago

I did the same thing and observed that the header is avaialble inside request while in controller HttpHeader i dont get it why?

@PostMapping(value = “/v0.2/card/add”)
public ResponseEntity<ResponseBody> addCard(HttpServletRequest request,
@RequestHeader HttpHeader

4 years ago

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

Previous article

Understanding Custom ThreadFactory In Java

Next article

Serialize Java object to JSON and back