Cookies and session tracking

From MyWiki
Jump to: navigation, search
You could send requests to a servlet and then forward requests to another servlet if needed.
In your case, after validation, you can store result in an attribute and then transfer control to another servlet. (if that's what you want to do)
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/urlToServlet");
dispatcher.forward(request, response);

And this is how to deal with cookies.

create and send cookies

Cookie userCookie = new Cookie("name", "value");
userCookie.setMaxAge(60*60*24*365); //Store cookie for 1 year
response.addCookie(userCookie);

read cookie from client

 cookieName = "somecookie";
Cookie[] cookies = request.getCookies();

if (cookies != null) {

   for(int i=0; i<cookies.length; i++) 
   {
       Cookie cookie = cookies[i];
       if (cookieName.equals(cookie.getName())) 
       {
           doSomethingWith(cookie.getValue());
       }
   }

} else {

   //do something else for firsttime visitors 

}

Are you using cookies for session tracking? If yes, then use HttpSession. Using HttpSession then there is not need to directly involve with cookies for session tracking.

For example, in a simple login page, this is what you do

HttpSession session = request.getSession();
session.setAttribute("username",username);
In other pages,
if(session.getAttribute("username")==null)
{
//forward to login page.
}