Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

request.getSession() always not null?

 
Kelvin Hung
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I have the following method taken from a book called The Struts Framework:
public boolean isSessionValid(HttpServletRequest request) {
if(request == null) return false;
HttpSession session = request.getSession();
if(session == null) return (false);
User user = (User) session.getAttribute(Constants.USER_KEY);
return ((user == null) ? false : true);
}
According to API, request.getSession() will return a new session if there is no session associated with the user. So (session == null) is always false, right?
Kelvin
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, theoretically getSession could return null if the request is actually a custom RequestWrapper instance, which overrides the default getSession behavior. Seems a pretty wierd thing to do, though.
 
Kelvin Hung
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so i guess in normal situation, if(session == null) is not needed since it is always false.
 
Ken Robinson
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If it read HttpSession ses = request.getSession(false), that would be understandable as this method returns null if a Session does not already exist. The zero arg method creates a new Session if one does not exist.
Probably a typo in the book.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic