Search code examples
jspcookiesforward

JSP doesn't show the Cookie immediatly after forwarding


I have the following problem: I have a few JSP pages. When I am on the main page I have the possibility to add a Cookie. In the CookieAdd page I add a Cookie and redirect myself with jsp:forward to the main page. Then the added Cookie should show up, but it doesn't show up immediatly. I have to reload the page to see the newly added cookie. How can I see it immediatly? Thanks, Tom.

<% Cookie c = new Cookie(request.getParameter("name"), ""); c.setMaxAge(0); response.addCookie(c); %> <html> <body>

`<jsp:forward page="Cookiemanager.jsp" />`

</body> </html>


Solution

  • You're not redirecting to the main page. You're forwarding to the main page. Forwarding happens completely at server-side. No new request is received by the server: the same, original request is simply handled by another JSP. So the cookie, that was not there in the original request, si still not there when this same request is handled by the second JSP.

    A redirect is completely different. Redirecting consists in asking the browser to go to another URL. If you did that, then the browser would receive the cookie as part of the redirect response, and would then send a new request, containing the cookie, to the new JSP.

    Note that the code you posted should not be in a JSP. A JSP is a view component. Its goal is not to set cookie or forward/redirect. Its goal is to generate HTML. Such code should be in a servlet, written in Java.