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

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.

Related

When session is considered accessed

Does calling HttpServletRequest.getSession(boolean create) cause the last accessed time of the session to be updated? What about getId() method or even calling getLastaccessedtime(). In brief, what is the criteria of accessing the HttpSession that cause the getLastAccessedTime to be updated
The Tomcat javadoc says this:
"Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT, and marked by the time the container received the request.
Actions that your application takes, such as getting or setting a value associated with the session, do not affect the access time."
So, based on what the javadoc says, the answers to your questions are (should be):
Q: Does calling HttpServletRequest.getSession(boolean create) cause the last accessed time of the session to be updated?
A: According to the javadoc, No. (But see below)
Q: What about getId() method or even calling getLastaccessedtime().
A: No.
Q: In brief, what is the criteria of accessing the HttpSession that cause the getLastAccessedTime to be updated.
A: See above. It records the time of the last client request for the session.
Note that the actual behavior is liable to depend on the Servlet implementation. For instance, according to the Tomcat 7 source code (7.0.39.2), a getSession(boolean) call will update the access time:
when the current Session is not already cached in the Request AND the request's session manager is able to map the sessionid to a valid Session, or
when create is true AND a Session is created.
It is not clear whether scenario 1. could actually happen in a call from application code, but scenario 2. certainly could. It means that creating the Session counts as an "access" ... which makes sense.
This pretty much depends on the implementation and configuration of the server. Like tomcat has setting in the source whether to set lastAccessedTime at the arrival of request or before sending response back.
Looking at Tomcat 7 source code answers are
HttpServletRequest.getSession(boolean create) updates lastAccessedTime ?
Yes
getId() updates lastAccessedTime ?
No
getLastaccessedtime() updates lastAccessedTime ?
No
Tomcat is updating lastAccessedTime by using access() method in the org.apache.catalina.session.StandardSession.
Below is source code for access() method
/**
* Update the accessed time information for this session. This method
* should be called by the context when a request comes in for a particular
* session, even if the application does not reference it.
*/
#Override
public void access() {
this.thisAccessedTime = System.currentTimeMillis();
if (ACTIVITY_CHECK) {
accessCount.incrementAndGet();
}
}
This method is called in HTTPServletRequest implementation of Tomcat class org.apache.catalina.connector.Request's getSession(boolean create) method. Same is true for simple getSession() call.
Following is the screenshot of call hierarchy of access()
From the Servlet Specification:
The
session is considered to be accessed when a request that is part of the session is first
handled by the servlet container.
That rules out all methods on the session immediately, as you already have to identify the session to associate the request with it, and it rules in getSession(boolean) if it creates a new session or first associates the request with the session.

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

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.

Sending the Session

I am currently doing a system on Google App Engine and am very new to it, I am developing using the Java plattform . I have a problem about sending the session object between servlets. I have already enabled sessions on the appengine.webxml. I can send the session object from my login page to a VIEW page but after which the session object cannot be passed any longer.
Any possible answers?
You do not need to "pass" a session object from one Servlet to another. The session object can always be retrieved via the HttpServletRequest e.g. like this HttpSession session = request.getSession();. In JSPs (I guess that's your view technology) you can access the session via the implicit variable session.
To make sure your session doesn't expire to early set an appropriate value for <session-timeout/> in your web.xml.

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);
}
}

Servlet Session - switch from URL Rewriting to Cookie

Situation: I have a "dumb" Javascript frontend that can contact some kind of SSO middleware (MW). The MW can obtain sessions by issuing requests that contain authentication credentials (username, password). I.e. the session will be created for a certain user.
My frontend needs to "restart" the session to gain the user's permissions to the target system. For that i need a valid session cookie.
The target system is not under my control (could be a more or less public WFS, WMS, etc.), so i cannot add any SSO mechanism to it.
Question: Is it possible to "steal" a Session forging a request which URL contains a valid session ID in the jsessionid parameter?
Goal : Issue such a request to a Servlet and make it respond with a Set-Cookie header that contains the same id. That way the frontend joins the session and may do whatever the user, which was used to create the session, is able to do.
Your best bet is a shared datasource (RDBMS?) where the shared information is stored with some long, auto-generated, unique identifier as key (java.util.UUID maybe?) and then pass this key around.

Categories

Resources