J2EE Programming

Hands On No. 6 : Working with Cookies and Session

Source Code of setCookie Servlet

Cookie ck=new Cookie("username","Dhaval Mehta");
response.addCookie(ck);

Source Code of getCookie Servlet

Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++)
{
out.print("<br>"+ck[i].getName()+"-"+ck[i].getValue());
}

Source Code of setSession Servlet

HttpSession session = request.getSession();
session.setAttribute("username", "admin");

Source Code of getSession Servlet

String s = session.getAttribute("username").toString();
out.println("Session ID: " + session.getId());
out.println("<br>Session Value: " + session.getAttribute("username"));
out.println("<br>Creation Time: " + new Date(session.getCreationTime()));
out.println("<br>Last Accessed Time: " + new Date(session.getLastAccessedTime()));