Thursday 24 July 2008

Java Session Cookies v HttpSession

Having written some Java Servlet code, which stored a string in a session cookie, I then looked into how HttpSession would compare and found I can get the same results with much simpler code.

My original session cookie code:

private String mySessionValue;

private String getMySessionValue(HttpServletRequest request) {
if(mySessionValue == null) {
Cookie[] cookies = request.getCookies();
if(cookies != null) {
for(int i=0; i < cookies.length; i++) {
Cookie c = cookies[i];
if (c.getName().equals("mySessionValue")) {
mySessionValue = c.getValue();
break;
}
}
}
}
return mySessionValue;
}

private void setMySessionValue(HttpServletRequest request, HttpServletResponse response, String newCookieValue) {
mySessionValue = newCookieValue;
Cookie cookie = new Cookie("mySessionValue", newCookieValue);
response.addCookie(cookie);
}

I had several issues with the cookie version,
  • I had to loop through the cookies to find my cookie
  • As the cookie value could be referenced after it was set, I had to store it locally too, as the actual cookie would not be updated until the responce is sent.
With HttpSession the code is much much less and no need to store the value locally:

private String getMySessionValue(HttpServletRequest request) {
HttpSession session = request.getSession(true);
return (String)session.getAttribute("mySessionValue");
}

private void setMySessionValue(HttpServletRequest request, String newSessionValue) {
HttpSession session = request.getSession(true);
session.setAttribute("mySessionValue", newSessionValue);
}

As well as much less code one main advantage to HttpSession is that it handles Objects not just Strings, so arrays can be stored much easier.

HttpSession wins I think.

No comments: