File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes request.getSession() vs request.getSession(boolean create) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "request.getSession() vs request.getSession(boolean create)" Watch "request.getSession() vs request.getSession(boolean create)" New topic

request.getSession() vs request.getSession(boolean create)

Em Aiy
Ranch Hand

Joined: May 11, 2006
Posts: 226

I am writing these lines from Java API

I am unable to understand the difference between 2. getSession() create a session if there is no session exist and getSession(boolean create) also creates a session if there is no session (if we pass TRUE). If the later function can perform the same functionalities then why the prior function is needed? or i am mis-interpreting the meanings and purpose of both function. Please explain out!

The difference between <b>failure</b> and <b>success</b> is often being <b>right</b> and being <b>exactly right</b>.
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

getSession(false) will not return a new Session if one does not already exist.

If your application needs to explicitly create and initialise a session, or you decide to use the existence of a session as detection of a logged in user, then you don't want to create sessions by accident. It is also useful as it can tell you where a user entered your application, ie if session==null then they didn't request another page before this one.
Em Aiy
Ranch Hand

Joined: May 11, 2006
Posts: 226
so does it mean that request.getSession() is just a wrapper on request.getSession(true);

mm, thanks!
Ben Souther

Joined: Dec 11, 2004
Posts: 13410

The implementation is up to the container builders but it seems like a pretty safe bet that that's how they do it.
If you really want to know, you can always grab the source to Tomcat, Jetty, Resin, or any other open source container and see for yourself.
[ July 24, 2007: Message edited by: Ben Souther ]

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
subodh gupta
Ranch Hand

Joined: Jul 23, 2007
Posts: 203
they are the overloaded methods with non-argument method calling the argumented method with default value
I agree. Here's the link:
subject: request.getSession() vs request.getSession(boolean create)
It's not a secret anymore!