tomcat-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Craig R. McClanahan" <>
Subject Re: Adding a cookie via a filterChain...
Date Fri, 16 Aug 2002 16:20:39 GMT

On Fri, 16 Aug 2002, Les Parker wrote:

> Date: Fri, 16 Aug 2002 10:00:14 -0600
> From: Les Parker <>
> Reply-To: Tomcat Developers List <>
> To:
> Subject: Adding a cookie via a filterChain...
> Does anyone have some example code that adds a cookie to the response
> header via a filterChain in tomcat 4.0??  I am at a dead end and would
> really appreciate some help...

Adding a cookie in a filter is the same as adding one in a servlet, and
suffers the same restrictions.  In particular, you won't be able to add
one after the response has been commited ... for example, this won't work:

    public class MyFilter implements Filter {

      public void doFilter(ServletRequest req, ServletResponse res,
                           FilterChain chain) {

        // Pass the request on
        chain.doFilter(req, res);

        // Now try to add a cookie
        ((HttpServletResponse) res).addCookie(...);



Because the servlet will have committed the response already -- and
cookies are sent in the HTTP headers, so they need to be added before

Another potential problem, even if you add the cookie before the response
is committed, is that a servlet can do RequestDispatcher.forward() -- or a
JSP page can do <jsp:forward> -- which will cause all the headers
(including your cookie) to be reset.

Details of how to deal with this depend on precisely what you're trying to
do, but may involve having to write a servlet response wrapper that
buffers the response data so that you can add the cookie after the fact
(with a potentially severe negative impact on performance).

> Thanks,
> Les Parker


To unsubscribe, e-mail:   <>
For additional commands, e-mail: <>

View raw message