1

I have used the following code to set cookie and then redirect.

String level=(String) request.getAttribute("level");

 if(level!=null)
 {
  Cookie cookie=new Cookie("level",level);
  cookie.setMaxAge(-1);
  cookie.setPath("http://localhost:8080/saml");

  response.addCookie(cookie);

  response.sendRedirect("http://​localhost:8080/saml/someservices.jsp");
 }


This code works fine. But I want to know how? Because when the jsp engine is parsing the jsp code, it will first encounter addCookie and the send redirect. Does it add the cookie as soon as the line response.addCookie(cookie); ? What if I give it the other way round i.e first sendRedirect() and then addCookie()? How does the jsp engine see this?

suraj
  • 1,828
  • 12
  • 36
  • 64

2 Answers2

7

Cookies are added to the HTTP response headers. The redirect is also specified in the headers. Both get sent back to the client when you send the redirect.

If you reverse the order of addCookie and sendRedirect, it might still work, depending on the exact sequence of events in the underlying servlet container. I wouldn't recommend it, though.

skaffman
  • 398,947
  • 96
  • 818
  • 769
-3

I would be surprised if the code works because the sendRedirect() method creates a fresh request and in this process everything in the previous response gets reset meaning that all the cookies will be lost. The new resource http://​localhost:8080/saml/someservices.jsp and its associated servlet (if any) will not be able to fetch the cookie called "level".

j0k
  • 22,600
  • 28
  • 79
  • 90
  • 5
    Your "surprision" is incorrect. It certainly works as per the HTTP specification. – BalusC Jan 11 '13 at 02:51
  • I've got this issue under MSIE9 (MSIE receives the cookie but is not sending it with the redirect request). I solved it by adding a P3P header with compact privacy policy, see http://stackoverflow.com/questions/7384502/ie9-loses-cookies-after-redirect – Julien Kronegg Oct 23 '13 at 12:18