Difference between revisions of "Cookies and session tracking"
From MyWiki
| Line 38: | Line 38: | ||
In other pages, | In other pages, | ||
if(session.getAttribute("username")==null) | if(session.getAttribute("username")==null) | ||
| − | { | + | { |
| − | //forward to login page. | + | //forward to login page. |
| − | } | + | } |
Revision as of 09:13, 24 May 2014
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
String 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.
}