What is session in Java? [duplicate]
Asked Answered
G

4

16

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.

Gladstone answered 8/9, 2010 at 13:23 Comment(1)
A session is associated with a single user. Two different user have different session. If you want to share something with same user then use setAttribute on session object. If between more than one use, then use context object.You can also share objects by attaching with a request object.Scotsman
D
22

Some [random] precisions:

  1. You don't need login/logout mechanisms in order to have sessions.
  2. 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.
  3. 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).
  4. 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.
  5. 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.
  6. Sessions are destroyed automatically if not used for a given time. The time-out value can be configured in the web.xml file.
  7. A given session can be explicitly invalidated using the invalidate() method.
  8. When people are talking about JSESSIONID, they are referring to the standard name of the HTTP cookie used to do session-tracking in Java.
Denunciatory answered 8/9, 2010 at 14:4 Comment(0)
Y
13

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.

Yolondayon answered 8/9, 2010 at 13:32 Comment(5)
Not really sure why this was downvoted.Wardship
Yeah, i know that. But i cant understand what will be stored in that variable 'ctx' & 'request'. Thats what i asked in there. What is WebContextFactory and WebContext? What will they do?Gladstone
Have you taken a look at the javadocs for those classes? HttpServletRequest: download.oracle.com/javaee/6/api/javax/servlet/http/…, WebContextFactory: jarvana.com/jarvana/view/org/directwebremoting/dwr/2.0.3/…, and WebContext: jarvana.com/jarvana/view/org/directwebremoting/dwr/2.0.3/…Yolondayon
JSESSIONID is not a request parameter.Denunciatory
I cant able to understand there, thats why i asked the professionals(stackoverflow), because, professionals can give practical view. Anyway, +1 for making me to read that documentation again.Gladstone
I
10

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 :

  1. User first logs onto website.
  2. Servlet container sets a COOKIE on the user's browser, storing a UNIQUE jsessionId.
  3. Every time the user hits the website, the JSESSIONID cookie is sent back.
  4. The servlet container uses this to keep track of who is who.
  5. 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

Ithnan answered 8/9, 2010 at 13:38 Comment(5)
Yeah, you have answered for half of my question. What i have to do, to invalidate a session(i.e how shall i remove session object for a particular person, who clicks Logout)?Gladstone
I believe session.invalidate() kills the session, so when the user next hits the site, they process will start over.Ithnan
Please note the session object is not a singleton shared by all users - each user has their very own object!Ithnan
Yea.. Yea... Now only i came to understand. Thanks for your answer.Gladstone
@All: Every answer for my question, clears my doubt inch by inch. Thats why, i love stackOverflow. Thanks to All.Gladstone
W
3

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);
}
}
Weanling answered 8/9, 2010 at 14:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.