Difference between request.getSession().getId() and request.getSession(false)? - java

What do these calls actually mean in terms of session?
System.out.println("print1: "+request.getSession().getId());
System.out.println("print2: "+request.getSession(false));
OUTPUT
print1: D94146A347D95563186EB7525726336B
print2: org.apache.catalina.session.StandardSessionFacade#d52411

HttpSession session = request.getSession(); Inside the service method we ask for the session and every thing gets automatically, like the creation of the HttpSession object. There is no need to generate the unique session id. There is no need to make a new Cookie object. Everything happens automatically behind the scenes.
As soon as call the method getSession() of the request object a new object of the session gets created by the container and a unique session id generated to maintain the session. This session id is transmitted back to the response object so that whenever the client makes any request then it should also attach the session id with the requsest object so that the container can identify the session.
request.getSession(false) : This method will check whether Session already existed for the request or not. If it existed then it will return the already existed Session. If Session is not already existed for this request then this method will return NULL, that means this method says that the request does not have a Session previously.

In short-
request.getSession().getId() - returns a string containing the unique identifier assigned to this session. The identifier is assigned by the servlet container and is implementation dependent.
request.getSession(false) - return session object or null if there's no current session.

First line will return the "session id" on server.
The second line will return session object. So what will be printed on system.out would be request.getSession(false).toString();
The default implementation of toString returns the "object id". Object id in terms of session is not the same as session id. Session could be serialized and replicated across the cluster so on each node of the cluster on each JVM it may have it's own object id (but should have same session id).
Calling get session with boolean is explained here:
http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getSession(boolean)

request.getSession()
This method will check for the existing session;if exist its return otherwise create a new session for the request.
request.getSession().getId();
This will return the unique identifier for that session.
request.getSession(false);
This method takes the boolean value.This method check whether there is an existing session present for that user(request);if exist it return that session otherwise it return null i.e it won't create new session.
Just to add more information for session.
request.getSession(true);
This method checks for the existing current session for that user(request) and if the session exist it will return that session or otherwise it create new session for that user.
request.getSession() works like request.getSession(true)
Reference :
http://docs.oracle.com/javaee/1.4/api/javax/servlet/http/HttpServletRequest.html#getSession%28boolean%29

request.getSession().getId()
Returs the id of the session.
Request.getsession(false) returns the already existing session object. It wont return anything i.e. Will return null , if session does not exist. Whereas with true parameter it will create a new session object and return it if no session exists

request.getSession().getId();
Will return unique string id assigned to already started session. Generation of id is vendor specific like apache, jboss etc.
request.getSession(false);
It will return session object associated to particular request if session object is associated it will be returned or it will return null if its is not started by server.

request.getSession().getId();
this will return the id of the an existing session.
Request.getsession(false)
it will return the session if it exists, or it will return null otherwise.
and Request.getsession(false) means : give me the session if it exists, otherwise do not create a new instance (and thus return null).

request.getSession().getId();
returns the unique identifier assigned to this session. And It has return type of String.
request.getSession(false)
returns the HttpSession object if it already exists else return null.

Related

request.getSession().getId() vs request.getRequestedSessionId()

What is the difference between request.getSession().getId() and request.getRequestedSessionId()? Do both of them return the same thing i.e. Session Id?
Thanks
request.getRequestedSessionId() will return the session id specified by the client (presumably in a cookie). request.getSession().getId() will return the server's session id (if a session does not exist, request.getSession() will create it).
The important difference is that you can't rely on the value returned by request.getRequestedSessionId(), since it may not be valid. From the documentation:
Returns the session ID specified by the client. This may not be the same as the ID of the current valid session for this request. If the client did not specify a session ID, this method returns null.
HttpRequest.getRequestedSessionId() is the session id provided by the caller, usually with the JESSIONID cookie whereas HttpRequest.getGession().getId() is the id effectively used by the server.
For an ongoing session, the JESSIONID cookie, or the value of HttpRequest.getRequestedSessionId() allows the server to find the ongoing session by id.
For new sessions, you might be very tempted to set the servers session id by supplying a value via the JESSIONID cookie, i.e. the value of HttpRequest.getRequestedSessionId(). This would make it easy to correlate a chain of calls to multiple servers initiated by an initial call from the customer's browser. However, the semantics of HttpRequest.getRequestedSessionId() does not allow such chaining.
Indeed, the JESSIONID cookie has an effect only for a session already existing in the server and which was previously sent to the client. If the JESSIONID cookie refers to a nonexistent session id, the server creates a new session ignoring the value of JESSIONID cookie.
You can convince yourself of the above, by reading the source code of the doGetSession(boolean) in the org.apache.catalina.connector.Request class.

check if session is valid or not in servlet

/****NOTE****/
in WEB.XML file I am setting session timeout property,
so may be session is expired.
/************/
I am using HttpSession object to manage session
HttpSesion session = myPersonalMethodThatReturnHttpSessionObject();
//I am using Eclipse and it provide me following details in Debug view I put Image Below
//so how can i get value of isValid field or method so here i can put in if condition
if(session != null)
{
//removing attributes from session
}
/*************************************More Description*******************************************/
My Problem is...
note1 --> session timeout is 30 min.
Step1 some one login my web apllication
Step2 session is created.
Step3 if user close web application without signout
Step4 all session attribute is there
Step5 if another user try to login.
Step6 I try to remove all session attribute and store new attribute value.
Step7 Above functionality work properly but, while session is invalidate can't remove session attribute so i need to put condition in if session is valid that remove attribute else do nothing so I need to check session is valod or not.
Since you are seeing isValid=false , I guess your session has become invalid/timedout.
You should be calling HttpSession session = request.getSession(true); or HttpSession session = request.getSession(); to always get the valid session.
The method request.getSession(true) will ensure that it will create a new session if the current session is invalid. If the current session is valid, it will return the same.
The method request.getSession(); by default calls request.getSession(true);.
Based on your update, your login process should be as follows:
HttpSession session = request.getSession(false); // returns null if no session or session is invalid
if(session != null) {
// you have old session
session.invalidate(); // invalidate session - this will remove any old attrs hold in the session
}
// create new session
session = request.getSession(); // creates new empty session
....
You cannot get the isValid field directly. The request.getSession(false) is using it and will return null, if current session is invalid. If session is already invalid you don't have to remove attributes, since they already have been removed and session is inaccessible any more.
you should create an concrete class which implement javax.servlet.http.HttpSessionListener and add your code into its two callback methods:
public interface HttpSessionListener extends java.util.EventListener {
void sessionCreated(javax.servlet.http.HttpSessionEvent httpSessionEvent);
void sessionDestroyed(javax.servlet.http.HttpSessionEvent httpSessionEvent);
}
remember to register your listener in web.xml!
You create session with HttpServletRequest object as follows.
HttpSession session = httpServletRequest.getSession();
This will give you new session if one is not already created or return existing session object.
somewhere in you method myPersonalMethodThatReturnHttpSessionObject() add the following line
HttpSession session = request.getSession(false);
This will help you to find valid session.

Why session is not null after session.invalidate() in JAVA?

I am facing very strange problem while developing JavaEE WEB Application.
Even after invalidating the HttpSession using session.invalidate();, I am not getting session null. There is a case where I have one statement in execution like below after invalidating session.
if (null != session && null != session.getAttribute("loginToken")){
//do something
}
I am not getting session null here so second condition will try to execute. And hence session is not null, so I am getting IllegalStateException - session is already invalidated. But why session is not null after invalidating it?? :(
Calling session.invalidate() removes the session from the registry. Calling getSession(false) afterwards will return null (note that getSession() or getSession(true) will create a new session in this case, see HttpServletRequest API). Calling invalidate() will also remove all session attributes bound to the session. However if your code still has references to the session or any of its attributes then these will still be accessible:
// create session if none exists (default) and obtain reference
HttpSession session = request.getSession();
// add a session attribute
session.setAttribute("lollypop", "it's my party");
// obtain reference to session attribute
Object lollypop = session.getAttribute("lollypop");
// print session ID and attribute
System.out.println(session.getId());
System.out.println(lollypop);
session.invalidate();
// session invalidated but reference to it still exists
if (session == null) {
System.out.println("This will never happen!");
}
// print ID from invalidated session and previously obtained attribute (will be same as before)
System.out.println(session.getId());
System.out.println(lollypop);
// print 'null' (create=false makes sure no new session is created)
System.out.println(request.getSession(false));
Example output:
1k47acjdelzeinpcbtczf2o9t
it's my party
1k47acjdelzeinpcbtczf2o9t
it's my party
null
So far for the explanation. To solve your problem you should do:
HttpSession existingSession = request.getSession(false);
if (existingSession != null && existingSession.getAttribute("loginToken") != null){
//do something
}
The invalidate method does the following (from API):
Invalidates this session then unbinds any objects bound to it.
It says nothing about the HttpSession-object itself, but invalidates the session's variables. If you call a method of a class, it is impossible for the object to be null after that method call. If your session should be null afterwards, the method must include a line that looks something like: this = null; which would not be possible. Throwing an exception for an invalidated session is the prefered way to do it.
Try passing false as the parameter to the getSession(boolean) . This will give back a session if it exists or else it will return null.
HttpSession session = request.getSession(false);
if(session==null || !request.isRequestedSessionIdValid() )
{
//comes here when session is invalid.
}

Store an object in session

I write the following code to store an object to the HttpSession:
JenaOWLModel jenaOwlModel=MyModelFactory.getJenaModel();
HttpSession session = request.getSession(true);
session.setAttribute("jenamodel", jenaOwlModel);
And get the oject in another servlet through the following code:
HttpSession session = request.getSession(true);
JenaOWLModel model=(JenaOWLModel)session.getAttribute("jenamodel");
It works well, but I want to know if the object I get from the session is the same object I put into the session or it's just a copy . If I change the object I got from the session, whether the object in session will also change? If it changes, will it need to synchronized the object in session by myself.Whether the tomcat provide a mechanism to synchronized the object in session automatically?
If I change the object I got from the session, whether the object in session will also change?
It's the same object, so of course it will change.
If it changes, will it need to synchronized the object in session by myself.
Yes.
Whether the tomcat provide a mechanism to synchronized the object in session automatically?
No.

What is session in Java? [duplicate]

This question already has answers here:
How do servlets work? Instantiation, sessions, shared variables and multithreading
(8 answers)
Closed 5 years ago.
So far I understand Httpsession concepts in Java.
HttpSession ses = req.getSession(true);
will create a session object, according to the request.
setAttribute("String", object);
will, bind the 'String', and value with the Session object.
getAttribute("String");
will return an object associated with the string, specified.
What I am not able to understand is: I am creating a session object like
HttpSession ses = req.getSession(true);
and setting a name for it by calling setAttribute("String", object);.
Here, This code resides inside the server. For every person, when he tries to login the same code in the server will be executed. setAttribute("String", object); in this method the string value is a constant one. So, each session object created will be binded by the same string which I have provided. When I try to retrieve the string to validate his session or while logout action taken the getAttribute("String"); ll return the same constant string value(Am I right!!?? Actually I don't know, I'm just thinking of its logic of execution). Then, how can I be able to invalidate.
I saw this type of illustration in all of the tutorials on the WEB. Is it the actual way to set that attribute? Or, real application developers will give a variable in the "String" field to set it dynamically
(ie. session.setAttribut(userName, userName); //Setting the String Dynamically.. I dono is it right or not.)
And my final question is
WebContext ctx = WebContextFactory.get();
request = ctx.getHttpServletRequest();
What do the two lines above do? What will be stored in ctx & request?
HttpSession ses = req.getSession(true); will creates new session means. What value stored in ses.
Some [random] precisions:
You don't need login/logout mechanisms in order to have sessions.
In java servlets, HTTP sessions are tracked using two mechanisms, HTTP cookie (the most commonly used) or URL rewriting (to support browsers without cookies or with cookies disabled). Using only cookies is simple, you don't have to do anything special. For URL re-writing, you need to modify all URLs pointing back to your servlets/filters.
Each time you call request.getSession(true), the HttpRequest object will be inspected in order to find a session ID encoded either in a cookie OR/AND in the URL path parameter (what's following a semi-colon). If the session ID cannot be found, a new session will be created by the servlet container (i.e. the server).
The session ID is added to the response as a Cookie. If you want to support URL re-writing also, the links in your HTML documents should be modified using the response.encodeURL() method. Calling request.getSession(false) or simply request.getSession() will return null in the event the session ID is not found or the session ID refers to an invalid session.
There is a single HTTP session by visit, as Java session cookies are not stored permanently in the browser. So sessions object are not shared between clients. Each user has his own private session.
Sessions are destroyed automatically if not used for a given time. The time-out value can be configured in the web.xml file.
A given session can be explicitly invalidated using the invalidate() method.
When people are talking about JSESSIONID, they are referring to the standard name of the HTTP cookie used to do session-tracking in Java.
I suggest you read a tutorial on Java sessions. Each user gets a different HttpSession object, based on a JSESSIONID request/response parameter that the Java web server sends to the browser. So every user can have an attribute with the same name, and the value stored for this attribute will be different for all users.
Also, WebContextFactory and WebContext are DWR classes that provide an easy way to get the servlet parameters.
As I understand it, your concerns are about separation of the different users when storing things in the HttpSession.
The servlet container (for example Tomcat) takes care of this utilizing its JSESSIONID.
The story goes like this :
User first logs onto website.
Servlet container sets a COOKIE on
the user's browser, storing a UNIQUE
jsessionId.
Every time the user hits the
website, the JSESSIONID cookie is
sent back.
The servlet container uses this to
keep track of who is who.
Likewise, this is how it keeps track
of the separation of data. Every
user has their own bucket of
objects uniquely identified by the
JSESSIONID.
Hopefully that (at least partially) answers your question.
Cheers
Your basic servlet is going to look like
public class MyServlet{
public doGet(HttpServletRequest req, HttpServletResponse res){
//Parameter true:
// create session if one does not exist. session should never be null
//Parameter false:
// return null if there is no session, used on pages where you want to
// force a user to already have a session or be logged in
//only need to use one of the two getSession() options here.
//Just showing both for this test
HttpSession sess = req.getSession(true);
HttpSession sess2 = req.getSession(false);
//set an Attribute in the request. This can be used to pass new values
//to a forward or to a JSP
req.setAttribute("myVar", "Hello World");
}
}
There is no need to set any attribute names for your session that is already done. As others have suggested in other answers, use cookies or URL re-writing to store the sessionID for you.
When you are dealing with the DWR WebContext, it is simply doing the same thing as above, just normally the Request object isn't passed into the method, so you use the WebContext to get that request for you
public class DWRClass {
public doSomething(){
WebContext ctx = WebContextFactory.get();
HttpServletRequest req = ctx.getHttpServletRequest();
HttpSession sess = req.getSession(); //no parameter is the same as passing true
//Lets set another attribute for a forward or JSP to use
ArrayList<Boolean> flags = new ArrayList<Boolean>();
req.setAttribute("listOfNames", flags);
}
}

Categories

Resources