Adding an HTTP Header to the request in a servlet filter
Extend HttpServletRequestWrapper
, override the header getters to return the parameters as well:
public class AddParamsToHeader extends HttpServletRequestWrapper {
public AddParamsToHeader(HttpServletRequest request) {
super(request);
}
public String getHeader(String name) {
String header = super.getHeader(name);
return (header != null) ? header : super.getParameter(name); // Note: you can't use getParameterValues() here.
}
public Enumeration getHeaderNames() {
List<String> names = Collections.list(super.getHeaderNames());
names.addAll(Collections.list(super.getParameterNames()));
return Collections.enumeration(names);
}
}
..and wrap the original request with it:
chain.doFilter(new AddParamsToHeader((HttpServletRequest) request), response);
That said, I personally find this a bad idea. Rather give it direct access to the parameters or pass the parameters to it.
Java Servlet filter: I have to add headers before passing to the chain, documentation tells otherwise
I do not know what version of the Servlet spec are you referring to, but in 3.1, chapter 6.2.1 "Filter Lifecycle" I read (emphasis mine):
- After invocation of the next filter in the chain, the filter may examine response headers.
"Examine" not "set"! Actually, the spec for the header methods says (Servlet 3.1, chapter 5.2 "Headers"):
To be successfully transmitted back to the client, headers must be set before the response is committed. Headers set after the response is committed will be ignored by the servlet container.
I guess this is happening to your request, some servlet or filter down the chain is "committing", so headers are ignored.
Bottom line: The spec (at least as far as I can see in 3.1) does not suggest to set the headers after calling chain.doFilter()
. Your second version that works is correct (and how I've always implemented filters that add headers)!
Adding header in response in filter?
After filterChain.doFilter
is called it's too late to do anything with the response. At this point, the entire response was already sent to the client.
You need to build a wrap response into your own classes, pass these wrappers into doFilter
method and handle any processing in your wrappers.
There is already a response wrapper: HttpServletResponseWrapper
that you can extend. For example:
public class MyResponseRequestWrapper extends HttpServletResponseWrapper{
public MyResponseRequestWrapper(HttpServletResponse response) {
super(response);
}
}
Your filter:
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
HttpServletResponse myResponse = (HttpServletResponse) response;
MyResponseRequestWrapper responseWrapper = new MyResponseRequestWrapper(myResponse);
responseWrapper.addHeader("Access-Control-Allow-Origin", "*");
filterChain.doFilter(request, myResponse);
}
How do you add a http protocol header value in HttpServletRequest ?
You can find the hooks in HttpServletRequestWrapper.
[Edited to include a link to an example]
Here you can find a fine example.
How we can modify headers in request Object using Filter
You can use javax.servlet.http.HttpServletRequestWrapper
to wrap the HttpServletRequest
object passed by the server.
In the wrapper class you need to override getHeader
method and return modified value of header.
You can refer to similar post over here Modify request parameter with servlet filter
Related Topics
What Is "Compiler Compliance Level" in Eclipse
How to Access Private Methods and Private Data Members via Reflection
Is There Any Performance Reason to Declare Method Parameters Final in Java
Exception in Thread "Main" Java.Util.Nosuchelementexception
Java Error: "Your Security Settings Have Blocked a Local Application from Running"
Java 8 Lambdas Group List into Map
How to Dynamically Add Items to a Java Array
Java: How to Indent Xml Generated by Transformer
Java: Convert String to Timestamp
How to Enumerate Ip Addresses of All Enabled Nic Cards from Java
Utf-8 Text Is Garbled When Form Is Posted as Multipart/Form-Data
How to Correctly Decode Unicode Parameters Passed to a Servlet
Getting Database Connection in Pure JPA Setup
Jsoup Character Encoding Issue
How to Read Properties File in Web Application