This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Servlets and the fly likes request.getSession() always not null? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "request.getSession() always not null?" Watch "request.getSession() always not null?" New topic

request.getSession() always not null?

Kelvin Hung

Joined: Jan 15, 2004
Posts: 29
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?
Frank Carver

Joined: Jan 07, 1999
Posts: 6920
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.

Read about me at ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Kelvin Hung

Joined: Jan 15, 2004
Posts: 29
so i guess in normal situation, if(session == null) is not needed since it is always false.
Ken Robinson
Ranch Hand

Joined: Dec 23, 2003
Posts: 101
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.
Don't get me started about those stupid light bulbs.
subject: request.getSession() always not null?
jQuery in Action, 3rd edition