This question already has answers here:
How do servlets work? Instantiation, sessions, shared variables and multithreading
(8 answers)
Closed 5 years ago.
1)
As mentioned here,
HttpSession objects must be scoped at the application (or servlet context) level, where context is,
ServletContext context = request.getServletContext();
2)
HttpSession object is created per browser session, in tomcat memory.
-----------------------------------------------------------------
Am unable to relate above two points.
An application is collection of different servlets. A servlet spawn a thread per connection from every browser. Every jsp/servlet points to a version of session object that the browser points to.
How can a session object that is created per browser gets scoped at web application level?
Session(or session id) is generated at server and transfer to browser through cookie or URL rewriting(when cookie is banned in browser).
In general, a session id is generated while user access the website. And after logging in, the server will change the session id for safety issues.
Session expired when:
(1)call session.invalidate()
(2)timeout configuration:
<session-config>
<session-timeout>xxx</session-timeout>
<session-config>
(3)Server restart(while the sessionid is saved in local cache)
Related
I am experimenting with setting the cookie path in my application's web.xml (as suggested here) to:
<session-config>
<cookie-config>
<path>/</path>
</cookie-config>
</session-config>
So I deploy two identical web applications to localhost:8080/application-a and localhost:8080/application-b respectively.
Each application is a single servlet:
public class ControllerServlet extends HttpServlet{
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
HttpSession session = req.getSession(false);
if (session == null) {
session = req.getSession(true);
System.out.printf("No session was present - new one created with JSESSIONID=[%s]\n", session.getId());
} else {
System.out.printf("JSESSIONID cookie was present and HttpSession objects exists with JSESSIONID=[%s]\n", session.getId());
}
}
}
I deploy the apps to a Tomcat 8.5 container (tried with Tomcat 9 as well the behavior is the same). When I visit with my browser the application-a, here's what I see:
… and on the Tomcat logs I read:
No session was present - new one created with JSESSIONID=[A227B147A4027B7C37D31A4A62104DA9]
So far so good. When I then visit application-b here's what I see:
… and the Tomcat logs show:
No session was present - new one created with JSESSIONID=[5DC8554459233F726628875E22D57AD5]
This is also very well as explained here and also in this answer and I quote:
SRV.7.3 Session Scope
HttpSession objects must be scoped at the application (or servlet
context) level. The underlying mechanism, such as the cookie used to
establish the session, can be the same for different contexts, but the
object referenced, including the attributes in that object, must never
be shared between contexts by the container.
So even though on the request the JSESSIONID cookie was present, my application (the one deployed in application-b) was unable to find an HttpSession object in its own servlet context scope and so a new session object was created and a new value was assigned to the JSESSIONID cookie.
However, when I now go back to my application-a I find out that because of the / value configured for the cookie path, it is now trying to use the JSESSIONID value set by application-b and of course its servlet doesn't find such a session object in its own context (application-a) and so a new value for the JSESSIONID cookie is created which will in turn invalidate the session of the application-b application and so on and so forth ad infinitum as I switch back and forth between the two applications.
So my questions are:
1 given the above behavior it would seem impossible for two applications to use the same JSESSIONID cookie value as the key to their respective HttpSession objects. So in fact not only are the HttpSession objects always different and scoped at the application (servlet context) level but also, in practice, the JSESSIONID values have to be different. Is that correct?
2 If so, then why does the servlet specification use the wording:
The underlying mechanism, such as the cookie used to establish the
session, can be the same for different contexts [...]
The only way I can imagine the above could be accomplished would be to have a way to hardcodedly provide the JSESSIONID value to use when a new session object is created? But I don't see an API for that.
3 Is there a way I can have some other cookies be shared among applications using the / path in the <session-config> XML element but not have the / path apply to the JSESSIONID cookie? In other words does the <session-config> apply to all cookies of an application or only the cookie used for session tracking? (JSESSIONID) ?
Upon further experimentation and taking a cue from this answer it would appear that for the same JSESSIONID to be used for all web applications it is necessary to set the following attribute in context.xml:
<Context ... sessionCookiePath="/">
Either the Tomcat-wide context.xml or the WAR-specific context.xml will do. The <cookie-config><path> value configured in the WAR's web.xml is apparently ignored.
Regarding point 3 of my question I 've found that the way to set paths for other cookies is to programmatically create many of them, one for each path, and add them in the response object with the addCookie method. The configurations in web.xml or context.xml are appicable to other cookies beyond the session cookie.
This question already has answers here:
How do servlets work? Instantiation, sessions, shared variables and multithreading
(8 answers)
Closed 7 years ago.
This is a pretty remedial question. I have not used the HttpSession class before. I am reading this tutorial, and I see that the session is a property of the HttpServletRequest.
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// get current session, or initialise one if none
HttpSession sess = req.getSession(true);
}
My question is, how does the session get stored? On the client? In the past I have been accustomed to storing the session server / database side. How does this work? If I update the session on a given request, will that always be reflected through subsequent calls? Is the session stored on the client?
how does the session get stored? On the client? In the past I have
been accustomed to storing the session server / database side. How
does this work?
A session can be defined as a server-side storage of information that is desired to persist throughout the user's interaction with the web site or web application.
Is the session stored on the client?
Instead of storing large and constantly changing information via cookies in the user's browser, only a unique identifier is stored on the client side (called a "session id"). This session id is passed to the web server every time the browser makes an HTTP request (ie a page link or AJAX request). The web application pairs this session id with it's internal database and retrieves the stored variables for use by the requested page.
when ever getSession() method is called it returns session if exists else it create a new session.apart from creating a session it does 5 things which you wont do.
You don’t make the new HttpSession object yourself.
You don’t
generate the unique session ID. You don’t make the new Cookie
object.
You don’t associate the session ID with the cookie. You don’t set
the Cookie into the response
All the cookie work happens behind the scenes.
If I update the session on a given request, will that
always be reflected through subsequent calls?
yes it effects the subsequent calls.
With a session cookie, or if cookies are disabled you're able to see the telltale JSESSIONID parameter. This was at least the case a while ago, and I shouldn't think it has changed.
The HttpSession is by default stored in memory and created/maintained by the web server (jetty, tomcat, ...). Depending on the web server you use you might have options like storing session information into the database.
Here is the tomcat documentation for the session manager[1]
[1] https://tomcat.apache.org/tomcat-7.0-doc/config/manager.html
This question already has answers here:
How do servlets work? Instantiation, sessions, shared variables and multithreading
(8 answers)
Closed 7 years ago.
I am new to Java EE. I have a site which requires a user to log in, and after the user logs in I would like the user to see his/her own item (e.g: shopping cart).
So that means I have to use a session to accomplish that. But how do I deal with multiple sessions?
For example multiple users login to the system as well as to the same servlet? However, can I keep multiple sessions in one servlet? Do I keep a record of each of them? How does it work?
Can someone give an example please ?
In servlet you have access to HttpServletRequest which provides you with a getSession() method. This methods returns session object (essentialy a key-value map), different for each user.
If you put something into that map (like shopping cart), you can retrieve it later - but only when the same user accesses the application again (not necessarily the same servlet).
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
session.getAttribute("cart");
//...
session.setAttribute("cart", whateverYouWant);
Sessions are maintained in the servlet container and looked up by session id (typically a cookie). You don't have to implement anything yourself.
Yes you can. The servlet container will keep track of them for you, so you shouldn't have to do that bookkeeping yourself. The Session object can be obtained from the HttpServletRequest in your servlet code. Since your code only has to concern itself with a single request at a time, there's generally not much pain in dealing with multiple sessions.
To deal with multiple users login in Servlets, create a session for each login as
HttpSession session = request.getSession();
public HttpSession getSession()
returns the current session associated with this request, or if the request does not have a session, creates one.
Each session will identify the users uniquely.
Now if user wants to change some data that is in database then after creating session, set attribute with that session with the information which can uniquely identify the user in database, for e.g. email_id as:
session.setAttribute("id",email_id of user);
This attribute can be retrieved later in another Servlet/JSP as:
String email_id = session.getAttribute("id");
This attribute will help in identifying the user who has sent request to server to update data in database or to do something else.
For more methods related to the session, refer the link:
http://www.javatpoint.com/http-session-in-session-tracking
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.
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);
}
}