This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach 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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "request.getSession() always not null?" Watch "request.getSession() always not null?" New topic
Author

request.getSession() always not null?

Kelvin Hung
Greenhorn

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

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 frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Kelvin Hung
Greenhorn

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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: request.getSession() always not null?
 
Similar Threads
Warning on session time out
Session creation
Session creates or not if we write request.getSeeion(false) for the first time
Session
Unable to get authentication and authorization working.