Reputation: 13
I have a simple jsp login page, and I am trying to implement the "remember me2 functionality. The jsp's page code:
String username = "";
Cookie[] vec = request.getCookies();
for(int i=0; vec!=null && i<vec.length; i++)
{
if(vec[i].getName().equals("userNameCookie")&&!vec[i].getValue().equals(""))
{
username = vec[i].getValue();
}
}
The form parameters are sent to the servlet controller, the controller creates the cookie and adds it to the response, and after that the controller forwards the request to the other page.
My issue is that after coming back to the login page the cookie that the controller adds to the response does not exist. In fact, the cookie exists in the page the controller forwarded the request to.
Here's the controller's code:
String username = request.getParameter("username");
String password = request.getParameter("password");
Cookie cookie = new Cookie("userNameCookie", username);
cookie.setMaxAge(7 * 24 * 60 * 60);
response.addCookie(cookie);
getServletConfig().getServletContext().getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
What am I doing wrong?
Thanks!
Upvotes: 0
Views: 202
Reputation: 57
At the first time of user send a request msg, the cookie you created in servlet has stored in response object, not in request object in jsp. You cant get the cookie from request object in your jsp which servlet forward to. Because the web container handle the forward before the send reponse msg to client agent. The client just store the cookie when it received reponse msg.
if the client resend the request, maybe it will done.
Upvotes: 0
Reputation: 692181
You must probably specify a path for your cookie. IIRC, if you don't specify one, the cookie is only valid for the URL the cookie comes from.
Also, your remember-me cookie is really insecure. Any user could authenticate himself as someone else by simply sending a cookie with the other user's name. You should make the cookie random and very hard to guess, and associate each random cookie with the user it has been generated for, in the database.
Upvotes: 2