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.

Advertisement

Entry filed under: java, maven, Uncategorized. Tags: .

Compiling Nano on Cygwin Define XML Element to Hold Text and Any Elements with XML Schema

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


Recent Posts

Categories


Follow

Get every new post delivered to your Inbox.