What servlet container are you running?  There was a bug in Tomcat 3.1 that
caused cookies (and other headers) set before a RequestDispatcher.forward() to
get wiped out, but this was fixed in 3.2.  You are doing things correctly.

In general, action classes in Struts will never generate any output going to
the response, so they will not be causing the response to be committed (unless
you were to call response.flushBuffer(), which you should *not* do before a
forward).  Therefore, it's entirely legal to set HTTP headers, as well as
cookies, in the action class ahead of the forward.

Craig


Pierre Métras wrote:

> Hi all,
>
> In the perform() function of my class, derived from ActionBase, I have the
> following code to set a cookie:
>
> public ActionForward perform(ActionServlet servlet,
>                                  ActionMapping mapping,
>                                  ActionForm form,
>                                  HttpServletRequest request,
>                                  HttpServletResponse response)
>         throws IOException, ServletException
>         {
>                     ...
>             Cookie cookie = new Cookie("userId",
> String.valueOf(userContext.getId()));
>             response.addCookie(cookie);
>             session.removeAttribute(mapping.getFormAttribute());
>             return mapping.findForward("result");
>         }
>
> It seems the cooky is never set.
>
> What's cool with open project is that you can look at the sources. Poking
> into the code, I found that the mapping ends with something like:
>
>         RequestDispatcher rd =
>             getServletContext().getRequestDispatcher(path);
>         rd.forward(request, response);
>
> But the javadoc for RequestDispatcher says "forward should be called before
> the response has been committed to the client (before response body output
> has been flushed). If the response already has been committed, this method
> throws an IllegalStateException. Uncommitted output in the response buffer
> is automatically cleared before the forward".
>
> So my question is: "how can I add a cookie to the response?".
> Either I add it and flush the response, then I should raise an
> IllegalStateException. Either I add it without commiting and then the
> response buffer (with all the headders?) is cleared before the forward.
>
> Pierre Métras

Reply via email to