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);
}
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.
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);
}
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:
Post a Comment