Is HttpSession in java servlet is created only after
HttpSession s = request.getSession();
?
In my code I didn't write that, but when I use if (request.getSession(false) == null) ...
, it doesn't work. Why?
Is HttpSession in java servlet is created only after
HttpSession s = request.getSession();
?
In my code I didn't write that, but when I use if (request.getSession(false) == null) ...
, it doesn't work. Why?
A HttpSession is created when calling request.getSession().
But if you access a JSP by default it will automatically create a session.This behaviour can be disabled by using:
<%@ page session="false">
Are you using JSP?
Try to remove session cookies from browser and make another test. If it does not work then some other component is creating a new session before that call.
To make it complete:
request.getSession()
, in your servlet, userequest.getSession(false)
to get existing session without creating new sessionsession
- unless you specify<%@ page session="false" %>
session.isNew()
to find out, if it has been newly createdRead JavaDocs, it says clearly:
This says, request.getSession()
And the other variant request.getSession(isCreate)
Update
On a bit research, I have found that Session is not created unless
request.getSession()
is called somewhere. Since,The servlet container uses this interface to create a session between an HTTP client and an HTTP server.
There are good chances that your Servlet container creates the Session for you by default.refer:
But, to be safer side, use
request.getSession()
to get session, and userequest.getSession(false)
only when you need to verify if a session has already been created.In addition to Nishant's answer note that session can be created implicitly by JSP pages unless you configured them not to create a session with
<%@ page session = "false" %>
.