Difference between revisions of "Cookies and session tracking"

From MyWiki
Jump to: navigation, search
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
 +
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");
 
  RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/urlToServlet");
 
  dispatcher.forward(request, response);
 
  dispatcher.forward(request, response);
Line 6: Line 8:
 
create and send cookies
 
create and send cookies
  
Cookie userCookie = new Cookie("name", "value");
+
Cookie userCookie = new Cookie("name", "value");
userCookie.setMaxAge(60*60*24*365); //Store cookie for 1 year
+
userCookie.setMaxAge(60*60*24*365); //Store cookie for 1 year
response.addCookie(userCookie);
+
response.addCookie(userCookie);
  
 
read cookie from client
 
read cookie from client
  
String cookieName = "somecookie";
+
  cookieName = "somecookie";
Cookie[] cookies = request.getCookies();
+
Cookie[] cookies = request.getCookies();
 
if (cookies != null)  
 
if (cookies != null)  
 
{
 
{

Latest revision as of 09:16, 24 May 2014

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.
}