I understand the difference between request.getSession(true) and request.getSession(false). But request.getSession() & request.getSession(true) look very similar!
Both "return the current session associated with this request", but differ in:
request.getSession():
"or if the request does not have a session, creates one"
request.getSession(true):
"if there is no current session, returns a new session"
I don't understand the difference between them, is it that (if none exists) they create a new session but the first one doesn't return it but the second one does?
Source: http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html
Edit:
Someone tagged/marked my question as duplicate even though it isn't. I will explain why.
I have explicitly asked for the difference between request.getSession() & request.getSession(true) and NOT between request.getSession(true) & request.getSession(false)! I have stated , again explicitly, that I already understand the difference b/w ..(true) & ..(false).
The question linked as a possible duplicated of of asks about the difference b/w ..(true) & ..(false) and not ..(true) & ..()
request.getSession() will return a current session. if current session does not exist, then it will create a new one.
request.getSession(true) will return current session. If current session does not exist, then it will create a new session.
So basically there is not difference between both method.
request.getSession(false) will return current session if current session exists. If not, it will not create a new session.
request.getSession() is just a convenience method. It does exactly the same as request.getSession(true).
Method with boolean argument :
request.getSession(true);
returns new session, if the session is not associated with the request
request.getSession(false);
returns null, if the session is not associated with the request.
Method without boolean argument :
request.getSession();
returns new session, if the session is not associated with the request and returns the existing session, if the session is associated with the request.It won't return null.
They both return the same thing, as noted in the documentation you linked; an
HttpSession object.
You can also look at a concrete implementation (e.g. Tomcat) and see what it's actually doing: Request.java class. In this case, basically they both call:
Session session = doGetSession(true);
A major practical difference is its use:
in security scenario where we always needed a new session, we should use request.getSession(true).
request.getSession(false): will return null if no session found.
request.getSession(true) and request.getSession() both do the same thing, but if we use
request.getSession(false) it will return null if session object not created yet.
request.getSession() or request.getSession(true) both will return a current session only . if current session will not exist then it will create a new session.
Related
I'm developing Java Servlets. At the point of checking whether a user is logged in, I want to check if the HTTP request has a valid session. For checking that, I have 2 possibilities:
(1)
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session != null) {
// user is logged in
...
}
}
Since I pass false as an argument, there is no new session created if there is no valid session existing already, and the function returns null, for what I can check.
Or I do:
(2)
if (request.isRequestedSessionIdValid()) {
// user is logged in
...
}
Is there any difference, any advantage/disadvantage? Or do both functions do more or less the same?
Form Javadoc
isRequestedSessionIdValid
boolean isRequestedSessionIdValid()
Checks whether the requested session ID is still valid.
If the client did not specify any session ID, this method returns false.
Returns:
true if this request has an id for a valid session in the current session context; false otherwise
So in sense both are same. But what you need to be aware of is request.getSession(false) will be null only in case of first request to the container. After the first request container creates a session and sends Jsessionid cookie along with response , so that it can track subsequent requests from the same browser. So in your case instead of checking if session is null or not, you should store a session attribute "is_logged_in"=true and check for this attribute as well if session is not null.
Based on the wording of the JavaDoc, it seems like there would be a distinction: if a valid session has already been created (from a prior call to request.getSession(true)), then the requested session ID will not be valid, but request.getSession(false) will have a valid (non-null) session to return. I haven't tested this theory.
I came across a code where the session object is obtained in two different ways (or rather wrote in two different ways).
using HttpServletRequest
someMethod(HttpServletRequest request){
HttpSession session = request.getSession();
//getAttribute from session
}
And using HttpSession
anotherMethod(HttpSession session){
//getAttribute from session
}
I went through this article and a question on SO. But i am still have some doubts.
Can someone help me understand what is the difference between these?
UPDATE
Both of these are methods in a spring controller and these are mapped to different ajax calls. I understand that there is a session associated with every request object but when you pass an HttpSession object where does it find the current session object(load all the attributes) or how is it obtained? When I call the method from javascript, I don't pass anything at all.
someMethod(HttpServletRequest request)
In this you are passing the current request object, from which you can obtain your current session and then you can get attributes from it.. You can get the current session object from your request object by using : -
request.getSession(false)
*NOTE: - We pass false as a parameter to getSession(false) to get any existing session.. If no session exist it will return null..
whereas, request.getSession() will always create a new session, so you won't get any prevoius attribute store in other session..
anotherMethod(HttpSession session)
Here you are passing the session object itself from somewhere.. Might be because, your session object contains many attributes, and you don't want to many parameters in the method..
But you should do all this session related task in your Servlet and pass the attribute to the methods of other class..
There is no huge difference between these two, the second method may be used if called multiple times to eliminate one extra method call request.getSession() by keeping session as somewhat like a local cache (with ignorable performance improvement unless called 100s of times).
eg,.
HttpSession session=request.getSession();
getFirstAttr(session);
getSecondAttr(session);
....
getHundredthAttr(session);
If you use the first method, then all the times that method is called one extra request.getSession() is called.
You don't need to float session objects if you have single attribute. Just simply access it using session object.
HttpSession session = request.getSession(true);
session.getAttribute(name);
Now only sensible case where you can float session objects is you have large number of attributes and you want each method to access its own set of attributes. In any case the method depends on session passed to it so it should not care how it was obtained.
String reqParam=request.getParameter("param");
if(reqParam!=null){
HttpSession session=request.getSession(false);
if(session!=null){
session.setAttribute("reqParamInSession", reqParam);
}
}
I use the code above to set a request parameter value into a session when a doFilter method is called. But when the user navigates to a different experience(assume a user that manages three different branches of a shop will have separate experience for each branch) the session is cleared other than the user profile. I don't manage the module that resets the session when the user experience is changed. But I still need the parameter I set in session even if the user has changed experience.
Is there a way to associate the parameter to every request sent regrdless of the session being changed? Or any other way to handle this?
Dont' use application scope as if the session is closed for any reason the params won't be cleared. Use cookies if you can.
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?
Read JavaDocs, it says clearly:
This says, request.getSession()
Returns the current session associated with this request, or if the request does not have a session, creates one.
And the other variant request.getSession(isCreate)
Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
If create is false and the request has no valid HttpSession, this method returns null.
To make sure the session is properly maintained, you must call this method before the response is committed. If the container is using cookies to maintain session integrity and is asked to create a new session when the response is committed, an IllegalStateException is thrown.
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:
Java Doc HttpSession
Discussion on JavaRaunch: is HttpSession created automatically?
But, to be safer side, use request.getSession() to get session, and use request.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" %>.
To make it complete:
session is not created, unless you call request.getSession(), in your servlet, use request.getSession(false) to get existing session without creating new session
if you use JSP page, session is automatically created for you - variable session - unless you specify <%# page session="false" %>
even if your session is created automatically, you can use session.isNew() to find out, if it has been newly created
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.
Hi just want to confirm when a session is expired in a webapp based on servlet.
The following session id will be available until the session is garbage collected, is that correct?
httpServletRequest.getRequestedSessionId()
Thanks,
C
if the session got expired, then at that point the session will be garbage collected and
httpServletRequest.getRequestedSessionId() will return new value when that method is called.
please check below url
http://download.oracle.com/docs/cd/E17802_01/products/products/servlet/2.1/api/javax.servlet.http.HttpServletRequest.html#getRequestedSessionId%28%29
When a session is expired getRequestedSessionId() return id new session which will be created when you call this method
To check if session is timed-out (in invalid state) check isRequestedSessionIdValid
From JavaDoc
getRequestedSessionId
public abstract String
getRequestedSessionId()
Gets the session id specified with this request. This may differ from the
actual session id. For example, if the
request specified an id for an invalid
session, then this will get a new
session with a new id.
Returns:
the session id specified by this request, or null if the request
did not specify a session id