Reputation: 1898
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?
Upvotes: 1
Views: 28633
Reputation: 403581
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.
Upvotes: 7
Reputation: 1
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".
Upvotes: -3