Add/Modify Header Values in Java HttpServletRequest using Servlet Filters
Steps to Modify Request Headers in a Servlet Request.
This example will demonstrate how to modify 'Content-Type' header in Java Servlet Filter.
In order to achieve this, use a custom wrapper Class, that extends HttpServletRequestWrapper.
Thereafter, we need to override certain methods inside this custom Class.
This example will demonstrate how to modify 'Content-Type' header in Java Servlet Filter.
In order to achieve this, use a custom wrapper Class, that extends HttpServletRequestWrapper.
Thereafter, we need to override certain methods inside this custom Class.
- getHeader(String name)
- getHeaders(String name)
- getHeaderNames()
- getParameter(final String name)
Code snippet for overriding above methods.
@Override
public String getHeader(String name) {
String header = super.getHeader(name);
if ("content-type".equalsIgnoreCase(name)){
System.out.println("Adds Header Content-Type as application/json");
return "application/json";
}
return header;
}
@Override
public Enumeration getHeaders(String name) {
List values = Collections.list(super.getHeaders(name));
if(name.equalsIgnoreCase("content-type")) {
values.add("application/json");
}
return Collections.enumeration(values);
}
@Override
public Enumeration getHeaderNames() {
List names = Collections.list(super.getHeaderNames());
names.addAll(Collections.list(super.getParameterNames()));
String url = new String(((HttpServletRequest)super.getRequest()).getRequestURL());
if(!names.contains("content-type"))
names.add("content-type");
return Collections.enumeration(names);
}
@Override
public String getParameter(String name) {
String paramValue = super.getParameter(name);
if (paramValue == null) {
paramValue = customHeaderMap.get(name);
}
return paramValue;
}
Comments
Post a Comment