How to Set an HTTP Header in a Tomcat Valve
September 14, 2010 at 5:24 pm Leave a comment
In Tomcat 6.0, it’s not obvious how to set an HTTP header in a valve (container-wide filter). You might think you could do it inside the invoke() method by calling the Request object’s addHeader(key,value) method, but you’d be wrong:-(
In the Tomcat source code, the addHeader() method is empty! It doesn’t even throw an exception to say it does nothing. That’s a nasty surprise left for you to discover by the Tomcat developers. Any way, here’s code for setting a header:
public void invoke(Request req, Response resp)
throws IOException, ServletException
{
MessageBytes mb =
req.getCoyoteRequest().getMimeHeaders().addValue("FOO");
mb.setString("BAR");
getNext().invoke(req, resp);
}
If you’re using Maven, you’ll need at least these two dependencies in your valve project:
<dependency>
<!-- has valve interface -->
<groupId>org.apache.tomcat</groupId>
<artifactId>catalina</artifactId>
<version>6.0.26</version>
<scope>provided</scope>
</dependency>
<dependency>
<!-- has ...coyote.Request -->
<groupId>org.apache.tomcat</groupId>
<artifactId>coyote</artifactId>
<version>6.0.26</version>
<scope>provided</scope>
</dependency>
Thanks to Mark Thomas’s response to a related post way back in 2006. Not being an HTTP protocol wizard, I’d not have connected HTTP headers with MIME types.
Entry filed under: java, maven, Uncategorized. Tags: .
Trackback this post | Subscribe to the comments via RSS Feed