duh ikal
duh ikal

Reputation: 162

Cookie set on the response by Servlet is not available in request of forwarded JSP

I have a simple page where a user would click a button and they would be forwarded to a new page. However accessing the new page without clicking on the button on the previous page can't be done. When the button is clicked it sends a cookie which checks if the button is clicked. This works fine if I use request.sendRedirect(). However when using request.forward() it doesn't. I have to click the button multiple times before I get sent over to the new page. Below is the code

//sends cookie when button is clicked
private void connect(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    Cookie cookie = new Cookie("connect", "connected");
    cookie.setMaxAge(1);
    
    response.addCookie(cookie);
    
    RequestDispatcher dispatcher = request.getRequestDispatcher("connectAudio.jsp");
    dispatcher.forward(request, response);
}

browser checks if cookie exists, if not then this indicates that the button has not been pressed and sends it back to page with button

<c:if test="${empty cookie['connect']}">
<c:redirect url="index.jsp">
</c:redirect>
</c:if>

Upvotes: 0

Views: 581

Answers (1)

haba713
haba713

Reputation: 2687

In case of redirect the browser sends two consecutive requests and the second one has the required cookie because it is set by the response to the first request.

In case of RequestDispatcher.forward(...) the browser makes only one request which is passed to connectAudio.jsp. The required cookie hasn't been set for this first request.

See this page and the image on it for more information:

enter image description here

Upvotes: 1

Related Questions