Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Cookie lost in RequestDispatcher

Status
Not open for further replies.

wolfmah

Programmer
Oct 24, 2001
17
CA
I am trying to set cookies in a controller servlet before dispatching to a JSP file, but the cookies are not set in the JSP file.

Servlet

Cookie cookie= new Cookie("userName", "wolfmah");
cookie.setMaxAge(60*60*24*7*1);
cookie.setDomain("wolfmahheaven.net");
response.addCookie(cookie);

RequestDispatcher rd= getServletContext().getRequestDispatcher("/cookie1.jsp");
rd.forward(request, response);

JSP (cookie1.jsp)

Cookie[] cookies= request.getCookies();

if (cookies != null) {
for (int i= 0; i < cookies.length; ++i) {
Cookie currentCookie= cookies;

if (currentCookie.getName().equalsIgnoreCase(&quot;userName&quot;))
out.println(currentCookie.getValue());
else
out.println(&quot;null&quot;);
}
}


The only output that I get is &quot;null&quot; two times because Tomcat seem to create 2 cookies itself, but mine isn't there.

 
request.getCookies() returns cookie set by the client browser. It will not contains any cookie that you just added to the response object within the same request session.

In other word, cookie won't appear until a round trip back from the client.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top