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);
}
}
Related
Is there a way to pass a parameter to a servlet going through another jsp and then to another servlet
like
jsp---parameter--->servlet(using getParameter())---parameter--->jsp---parameter--->servlet(is there a way to get the parameter here)
The program that am working on is to pass the username.
Looks like you want to use HTTPsession.
Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.
The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user. A session usually corresponds to one user, who may visit a site many times. The server can maintain a session in many ways such as using cookies or rewriting URLs.
Setting
Session session = request.getSession();
session.setAttribute("username", username);
getting it back
String username = (String)session.getAttribute("username");
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
In one servlet I have four variables. I want all those four variables to be retrieved to another servlet.
I used the code in servlet 1 as follows.
import javax.servlet.http.HttpSession;
session.setAttribute("id",id);
In the other servlet I tried to get the value by using the code..
String id = HttpSession.getAttribute("id").toString();
I think there is a clear way to do the tracking of the session variables.
I have seen in net but all are confusing to me..
Please help me..
First you need to get the Session object from the request.
This is the HTTPServletRequest object sent to the servlet (you will have access to this in the doGet or doPost method).
to set:
ses = request.getSession(true);
ses.setAttribute("Name","Value");
to retrieve:
request.getSession(false).getAttribute("name")
getSession(true) means create session if one does not exist. getSession(false) is equal to getSession. Finally if you wish to remove the attribute from the session from that point you can use
request.getSession().removeAttribute("Name");
I hope this makes sense to you if you need more look at Java Set, Get and Remove Session Attributes.
TomRed
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.