Adding Header Information to an existing HTTP Request

Servlet API doesn’t allow modifying the header information of an existing HTTP Request. The API does not allow ‘addHeader’ method.

Consider a situation where you need to add a token to all existing HTTP request, which will be used by other controllers or servlets for authentication or authorization.

One good example is SSO, where the encrypted user credentials can be stored as the part of HTTP Request.

Following is the simple way to modify the existing HTTP Request.

  • Create a Filter or Controller Class in which the existing request need to be modified.
  • Create a class which extends ‘HTTPServletRequestWrapper’ (This class is provided by Servlet API for creating custom request objects). Sample code is shown below.
  • Provide addHeader method to this class.
  • Override getHeader(s) methods.
  • Create an instance of newly created class.
  • Modify the new object using addHeader method.
  • Pass the new object to the next chain instance in the Filter or Controller chain list.

Note: Make sure you are not corrupting the existing request (unless required).

Sample Code

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class CustomHttpServletRequest extends HttpServletRequestWrapper {

private Map customHeaderMap = null;

public CustomHttpServletRequest(HttpServletRequest request) {
customHeaderMap = new HashMap();
public void addHeader(String name,String value){
customHeaderMap.put(name, value);

public String getParameter(String name) {
String paramValue = super.getParameter(name); // query Strings
if (paramValue == null) {
paramValue = customHeaderMap.get(name);
return paramValue;


public class CustomRequestFilter implements Filter {
public void doFilter(ServletRequest sreq, ServletResponse sresp,
FilterChain fchain) throws IOException, ServletException {
CustomHttpServletRequest request = new CustomHttpServletRequest((HttpServletRequest)sreq);
request.addHeader("ssoid-token", encrypt("dummy"));
fchain.doFilter(request, sresp); //New Request Object is passed