I understand that if we use the following statement
HttpSession session = request.getSession();
Will create the Unique session id, Create Cookie and associate Cookie with the Session id.
and helps the container to keep track and identify the clients.
Yes, My question, is there a possibility for me to see the cookie header and Unique Id created by this statement request.getSession()?
You can retrieve a HTTP Header using
HttpServletRequest.getHeader.
Although a session can be created by calling HttpServletRequest.getSession(true)
it's rather done by the webcontainer. As edl already wrote HttpServletRequest.getSession().getId() returns the session id.
You can see it using any HTTP header tracker tool. Firebug for example shows the headers in the Net panel. Here's a screenshot (click here for full size):
Any newly created cookie will appear as Set-Cookie header in the response. The client will send the same value back as Cookie header in the subsequent requests in the same session so that the server can identify the client session. For a JSP/Servlet webapplication, your interest is the cookie with the name JSESSIONID.
You can use session.getId() for the ID I believe. Not sure about the header.
I found more information in the following URL
http://www.javacertifications.net/javacert/session.jsp
Related
When user access a website for the first time, the initial server response may include a SET-Cookie header to set the session ID. Such as:
Set-Cookie: JSESSIONID=04427E42C4AE7A5DD1CCE86B8B5F7110; Path=/TestSite/; HttpOnly
Then client will carry it in cookie header for subsequent HTTP requests: Such as:
Cookie: JSESSIONID=04427E42C4AE7A5DD1CCE86B8B5F7110
My question is:
So the real session object is some data structure created and maintained on server. Server just send its index key to client. When subsequent requests come, server will use that key to find session data store on server. And if necessary, server can use database to store the session data. Is this mind picture correct?
The following Java code is actually manipulating the session data which is stored on server. Though it looks like it is manipulating the request object. Right?
request.getSession().setAttribute("accountId", user.getId());
The following code is essentially key (sessionid) looking up process. It looks for a session object on server by looking up for a session id cookie sent from client. Right?
Session s = (String) request.getSession();
Is there any chance server doesn't send the Set-Cookie header? Or is it mandatory?
It seems some key-value store like Redis is very suitable for session store. Has anyone tried that?
So the real session object is some data structure created and maintained on server.
With a servlet session, yes. But in general, you could also store "real data" in the session cookie itself. Has the downside that the user can see it and mess with it, and that it can only be quite small, but has the advantage that the server does not have to store the state (and share it with others in a cluster).
The following Java code is actually manipulating the session data which is stored on server
That's right. The Servlet API provides for this interface through the request, because that way it is associated to the session key (and the individual user).
Is there any chance server doesn't send the Set-Cookie header? Or is it mandatory?
You could turn that off. If you need sessions, but don't want cookies, it gets a bit complicated. You could attach a query parameter to every URL.
It seems some key-value store like Redis is very suitable for session store. Has anyone tried that?
Yes, that's a common setup.
The default setup for servlet containers is to store the session in memory. This does not need any configuration or preparation, but works well only for single-server deployments. If you have more than one server, you need to either share the session information (using something like Redis), or have "sticky session" (configure the network to always send the same user to the same server).
I have a legacy Java 1.6 running localhost with Tomcat 7 application using JSP pages, a frameset with frames, javascript, but no framework like Struts. I pass an object to display in the page from the servlet using the request or session and that works fine.
However, I made some changes recently and now I can't retrieve that same object back from the session or request. It had been working fine previously, so I'm not sure what is broken, but I can't even send a string value back from the JSP's back to the servlet.
I created a new stripped down JSP and I can't get anything back from that either using the request or session. It does the same thing when I push the code our Tomcat 6 web server. Using the debugger, I see the objects populated in the session, but then lost later when a new session is created each time as in using this simple code to get the sessionid:
System.out.println("The session id is: " + session.getId());
The session id is: EB431C19B41957B2BB2EFC3DBAF32241
The session id is: C9CBD30E84D5C93DF6114C1412AE5523
I then see this in firebug under the Header, response headers:
Set-Cookie JSESSIONID=C9CBD30E84D5C93DF6114C1412AE5523; Path=/Name omitted here/; HttpOnly,
so I know cookies are set. I also removed jquery and I"m stripping down the jsp code as much as possible, but that doesn't seem to be the issue.
I'm using:
HttpSession session = request.getSession(true); but using false didn't matter.
session.setAttribute("ObjNameList", objNameList);
The context.xml has cookies set to true and we do use response.sendRedirect, but only if an error is thrown as in: response.sendRedirect("Error.jsp"); There is no place in the code with session invalidate either.
All I'm doing from the jsp is sending a form back using something like:
document.formName.submit(); which works fine. Using this code to try and set a simple string in the session doesn't work either:
session.setAttribute("somevalue","someValue");
Gives me null in the servlet here:
String val = (String) session.getAttribute("somevalue");
Any ideas as to what could be causing this?
Resultion:
It turned out to be an issue with the url, a typo actually, as BalusC mentioned, so the path for the session cookies didn't match between the jsp and the servlet.
Doublecheck if the request URL to that servlet matches the session cookie domain and path. If it doesn't match, then the browser simply won't send the session cookie back along with the request and the server will think that there's no means of an established session and will therefore simply create a new one.
You can check cookies in the HTTP traffic monitor of browser's web developer toolset (press F12 in Chrome/Firefox23+/IE9+ and open "Network" tab). When a new session starts, the server must have returned a response with Set-Cookie header with therein the cookie value and path (and implicitly domain). When the browser sends a subsequent request on the same domain and path, then it must have passed that cookie back via Cookie request header.
See also:
How do servlets work? Instantiation, sessions, shared variables and multithreading
We have the following situation:
JSESSIONID is being sent by both cookies and URL, but because of a Adobe Flash BUG, they are different (actually, the cookie JSESSIONID is wrong).
What we would like to do is to use the URL JSESSIONID instead of the one sent in the cookies. In other words, when I execute request.getSession(), it should return the HttpSession associated to the ID in the URL and not in the cookie.
We looked into Tomcat7 source code and, in fact, Tomcat first parses the URL, searching for an identifier. Then it overrides it with cookies SESSIONID if they are present. Here is the code snipped in CoyoteAdapter.java (tomcat 7.0.26):
String sessionID = null;
if (request.getServletContext().getEffectiveSessionTrackingModes()
.contains(SessionTrackingMode.URL)) {
// Get the session ID if there was one
sessionID = request.getPathParameter(
SessionConfig.getSessionUriParamName(
request.getContext()));
if (sessionID != null) {
request.setRequestedSessionId(sessionID);
request.setRequestedSessionURL(true);
}
}
// Look for session ID in cookies and SSL session
parseSessionCookiesId(req, request);
parseSessionSslId(request);
We could disable cookies JSESSIONID at all, but we can't because we use it for all URLs in the website. We'd like to disable cookies for JUST THIS SPECIFIC URL.
Is it possible? Is there any other idea or workaround to solve this problem?
You could implement a custom servlet filter that would replace request, response and session objects with your own wrappers. The wrappers then can behave differently based on the URL, e.g. delegate or not to the original session instance. Though you won't be able to access session data for some other id, without changing Tomcat code.
I have a very basic question how the creation of HTTPSession works.I know you folks will fire me on looking at this question as similar kind
of questions exist.But there is reasoning why i am asking this question Here it is :-
I know httpsession is unique to web browser and server creates it when we do HttpServletRequest.getSession first time.It will maintaintain the same session till we
close the browser. But i have little bit different scenario.I Have a web application on one tomcat instance say T1.On welcome page of this web application
i have provided two links on click of which takes me to same java servlet(S1) of different web application hosted on another tomcat instance T2 (these two links
opens two seperate pop up windows). Now first i click the link1 and inspect the sessionId in S1 and find its value as 1678. Now first i click the link2 and
inspect the sessionId in S1 and find its value again as 1678. My question here is why i am getting the same session id for both the requests origintaing
from link1 and link2? what can i do to to get the different session for both of these requests?
What i tried after looking for possible solutions on net :- On click of link1, in Servlet S1 , i copied session attributes, invalidate it and create new one.
Say new session id is 8765 . Now i click the link2 and found the same session in this request too. So i further invalidate it and creates new one(say
new session id is 4897). Ideally it should expire the first browser session (generated on click of link1). To verify it,i click anywhere on pop up 1 it does not get
expired but i see again last generated session id i.e 4897. I am not getting why it attaching the same session id with both pop up windows?
Folks Thanks for your patience for taking your time out and read this long scenario?
Edit :-
Cookie[] cookies = req.getCookies();
if(cookies!=null)
for (int i = 0; i < cookies.length; i++) {
cookies[i].setMaxAge(0);
context.getResponse().getHttpServletResponse().addCookie(cookies[i]);
}
HttpSession myAppSession = req.getSession();//line 1
Assume on click of link1 i get session id as 1234,then after click of link 2 also i get the same session id. As per my understanding, after executing the code above line 1 , i should get the different session id as i am setting the MaxAge as0 before getting the session. But its not happening?
I think this is what you are looking for :
By default session tracking happens by cookies. WebServer sends the session id to the browser in the form of cookie. And, the browser send the cookie having session id for the subsequent requests.
How does the browser identifies which cookies to send for a link/request?
It is based on the these parameters. If the request matches these paramters the browser sends that particular cookie:
Domain: The domain name to which the request is made. Verify in your case if the domain name is same for two instances
Path: If the path name is same. Web Server send the context root as the path , requests under same context root share cookies.
Secure: Server sends if the given cookie is secure or not. Meaning, if the cookie can be sent on non-secure channel.
These parameters will let the browser to send the cookies to the server. And because the same cookie is sent for both the instances you are having. I think the session id is being shared.
If the request propeties such as Request URI, domain and path(i.e, context root) are same between requests, there is no way to tell the browser to use different cookies.
You have some options below:
Use different domain names.
Use different context roots.
Have a LB in front of two nodes and redirect to the correct node based on Session id
I'm new to Java. I'm writing an application to link to a vendors Flash site. I have my BlazeDs based program talking to their site. I'm running into a problem where a session cookie is not getting set. The problem is that the host doesn't return it as a "set-cookie" header.
Their site returns the following cookieDirectives to set the SMSESSION cookie
cookieDirectives
Externalized Object
flex.messaging.io.ArrayCollection
[0] String SMSESSION={CONTENT STRIPPED FOR CLARITY}; max-age=-1;path=/; domain=.-----.com
I can set the cookie in my amfConnection as follows:
amfConnection.addHttpRequestHeader("Cookie", resultString);
However, that only gives me the one cookie and there are several others I need. The others have been set earlier by the host and are set using a "Set-Cookie" header.
How can I either add this cookie to the existing ones or recover the existing cookies so I can manually add them.
I was able to resolve this by changing my approach. Instead of relying on my amfConnection to handle the cookies I grab the session id using httpclient, store it in a variable, and then push my cookies to amfConnection.