PDA

View Full Version : What to mess up cookies in the request & response?


vw729
Mar 28th, 2007, 03:24 PM
Here is my problem occurred in the user sign in logic:

After a correct sign in, the user ID is also stored in a cookie for the future reference in the sign in method of a MultiActionController. Then, it is redirected to another method of the same class to download the user preference data. In this method, I place a segment of code for retrieving all cookies for a testing purpose. It can't find any cookies at all although there are some application cookies such as session ID cookie placed by the Tomcat.

String email = request.getParameter("email");
String password = request.getParameter("password");
User account = service.getAccountByEmailAndPassword(email, password);
if (account != null) {
// ...
Cookie c = new Cookie("user_cookie", userSession.getUser().getId().toString());
c.setMaxAge(86400);
c.setPath("/");
response.addCookie(c);
// ...
}
return new ModelAndView(new RedirectView("/account/home.htm", true));
// ...

And in the following method

logger.debug("");
Cookie[] cookies = request.getCookies();
if (cookies != null) {
logger.debug(cookies.length);
for (int i = 0; i < cookies.length; i++) {
logger.debug("Finding Cookies: " + cookies[i].toString()); // line 1
if (cookies[i].getName().equals("user_cookie")) {
logger.debug("Cookie found: " + cookies[i].toString());
}
}
}
// ...

The line 1 is not reached. In the other words, no cookie is in the request at all. Can anyone explain why the cookie can't be set in the first method and why no cookie is detected in the second method.

Thanks very much for your inputs.

vw729
Mar 29th, 2007, 06:20 PM
I am aware that it is not a Spring issue. So, I did a search on the Struts mailing list archive. Here is what I found:

One option would be to use a <forward> that does a sendRedirect() instead
of a RequestDispatcher.forward(). This would cause the cookie to be
deleted, at the expense of being able to pass request attributes back to
page1.jsp again -- you'd need to use session attributes now.

Craig McClanahan


I found a valid (for me) reason to choose redirection over forwarding.

As part of switching to using cookies for user tracking ...

When setting a cookie in an action, I was orginally forwarding to the
next page and then wondering why I couldn't see the cookie that I had
just set. This is because there had been no round-trip back to the
browser to set the cookie and then send it when it requested the next
page. So in my action I directed the returned actionforward to use
redirection and while it is a little less efficient for that one page
transition, I do now get my cookie set and am able to read it in the
next page.


I, however, do not use forward, but redirect. And cookies are still missing.

cmelgar
Mar 29th, 2007, 08:56 PM
A bit of a stab in the dark, but maybe try checking browser settings to ensure the cookies are not being rejected.

Chris