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.
- 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.
- 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.