Lifetime of java httpsession - java

According to http://www.ibm.com/support/knowledgecenter/SSAW57_7.0.0/com.ibm.websphere.nd.multiplatform.doc/info/ae/ae/cprs_best_practice.html?lang=en
Avoid trying to save and reuse the HttpSession object outside of each servlet or JSP file :
The HttpSession object is a function of the HttpRequest (you can get
it only through the req.getSession method), and a copy of it is valid
only for the life of the service method of the servlet or JSP file.
You cannot cache the HttpSession object and refer to it outside the
scope of a servlet or JSP file.
I don't understand as here it is said the contrary : https://docs.oracle.com/cd/E11035_01/wls100/webapp/sessions.html
Session tracking enables you to track a user's progress over multiple servlets or HTML pages

The one from Oracle is good. If for example you set the session attribute "USER" when the user logs in, the user's session is available across all the pages. The session expires based on the time you configure in your web.xml environment for example when you use Tomcat.
Here is what I found from the doc :
https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpSession.html
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.
Hope it helps!

Related

Servlet session without cookies + ajax requests that only return JSON

Here's my situation, I have a web site that I just load using Apache HTTPD that then makes Ajax POST requests to a servlet which returns only JSON data. That JSON data is then used to update tables, etc..
Now I want to add user logic to my site, and also maintain servlet sessions for requests made by individual users.
I understand that the servlet needs to return the session id generated by the first call to request.getSession(), so that the client can add this sessionid to future Ajax requests in order for the servlet to know which session in memory to use.
I also understand that the two ways that this session id can be returned to the client is either using cookies (JESSIONID) or URL Rewriting.
If I can't use URL Rewriting, because I'm just returning JSON data, are cookies the only way I have left to send back the session id to the client?
Also, as a side question, currently I noticed that there is no JSESSIONID cookie in any of my HTTP responses from the servlet. Someone suggested to me that this was something new in Tomcat7 and that I had to activate them in the global context.xml. Does this mean that by default there is no session handling even if you make calls to request.getSession() ?
You have correctly identified two of the three ways of handling session IDs supported by Tomcat. There is a third way to track sessions but only if the application runs over SSL. In that case you can configure Tomcat to use the SSL session ID.
If the Servlet calls request.getSession() then Tomcat always includes a session ID in the response. However, those cookies are marked as httpOnly by default in Tomcat 7 onwards which means they are not visible to javascript (to protect against XSS attacks that try to steal the cookie). If the session cookies need to be visible to script then you need to set useHttpOnly="false" in either the web application's context.xml (to change the default for just that file) or in $CATALINA_BASE/conf/context.xml to change the default setting for every web application.

How to handle multiple clients in JSP?

I'm implementing a game in JSP and Servlets. The game should support multiple players.
It is obvious that each player ID is generated on the server side. But where do I store it on the client side, so I can retrieve it later (from within the servlet) when the client calls for the Servlet?
Sessions are handled automatically by the servlet framework, and you retrieve the session by calling request.getSession() in a servlet.
The session is available in different ways once you start using a framework once you outgrow servlets (this happens quickly) and is framework-dependent.
Depends on how long you want the client to remember the player ID.
During the session: The session is a good place
During his subsequent visists: A (permanent) cookie is a good place
Session: request.getSession()
Cookie: request.getCookies() and response.addCookie(cookie)
Session ids are usually stored in a cookie.
I'd be amazed if JSP doesn't have a session library that would take care of all that for you.

What is session management in Java?

I have faced this question in my Interview as well. I do have many confusion with Session Scope & it management in java.
In web.xml we do have the entry :
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
What does it indicate actually ? Is it scope of whole project ?
Another point confusing me is how can we separate the session scope of multiple request in the same project? Means if I am logging in from a PC & at the same time I am logging in from another PC, does it differentiate it ?
Also, another confusing thing is the browser difference. Why does the different Gmails possible to open in different browsers ? And Gmail can prevent a session from Login to Logout. How is it maintained with our personal web ?
Session management is not something limited to Java and servlets. Here's roughly how it happens:
The HTTP protocol is stateless, so the server and the browser should have a way of storing the identity of the user through multiple requests
The browsers sends the first request to the server
The server checks whether the browser has identified with the session cookie (see below)
3.1. if the server doesn't 'know' the client:
the server creates a new unique identifier, and puts it in a Map (roughly), as a key, whose value is the newly created Session. It also sends a cookie response containing the unique identifier.
the browser stores the session cookie (with lifetime = the lifetime of the browser instance), containing the unique identifier, and uses it for each subsequent request to identify itself uniquely.
3.2. if the server already knows the client - the server obtains the Session corresponding to the passed unique identifier found in the session cookie
Now onto some the questions you have:
the session timeout is the time to live for each session map entry without being accessed. In other words, if a client does not send a request for 30 minutes (from your example), the session map will drop this entry, and even if the client identifies itself with the unique key in the session cookie, no data will be present on the server.
different gmails (and whatever site) can be opened in different browsers because the session cookie is per-browser. I.e. each browser identifies itself uniquely by either not sending the unique session id, or by sending one the server has generated for it.
logging from different PCs is the same actually - you don't share a session id
logging-out is actually removing the entry for the session id on the server.
Note: the unique session id can alternatively be stored:
in a cookie
in the URL (http://example.com/page;JSESSIONID=435342342)
2 or 3 other ways that I don't recall and aren't of interest
What does it indicate actually ?
The lifetime of a session. The session expires if there is no transaction between the client and the server for 30 minutes (per the code segment)
Is is scope of whole project ?
It has application scope. Defined for each web application
Another point confusing me is how can
we separate the session scope of
multiple request in the same project?
Means if I am logging in from a PC &
at the same time I am logging in from
another PC, does it differentiate it ?
Yes. The session ids (JSESSIONID for Apache Tomcat) will be different.
Also, another confusing thing is the
browser difference. Why does the
different Gmails possible to open in
different browsers ?
Each login by the same user from a different browser is a different session altogether. And the cookies set in one browser will not affect in another. So different Gmail instances are possible in different browsers.
And Gmail can prevent a session from
Login to Logout. How is it maintained
with our personal web ?
Persistent cookies
Servlets in Java have an HttpSession object which you can use to store state information for a user. The session is managed on the client by a cookie (JSESSIONID) or can be done using URL rewrites. The session timeout describes how long the server will wait after the last request before deleting the state information stored in a HttpSession.
The scope is per browser instance, so in the example you give logging in from two different pcs will result in two session objects.
if you open the same application in different window i mean multiple instance of a browser it will create different session for every instance.
I recommand Apache Shiro for session management,Authentication and authorization.
I take it back.
As #BalusC commeneted below, only servlet container is in charge of managing the http session. Shiro is just using that. It will hook to HttpSession via a filter you explicitly define.
we have 4 ways to manage a session.
1.Cookies
2.URL rewriting
3.Hidden form fields
4.HTTP session
the fourth one is powerful and mostly used now-a-days.

Servlet Session behavior and Session.invalidate

Suppose I have a web app with a servlet defined in web.xml.
Then I deploy it on Tomcat.
Then I open my browser and go to the link to this servlet, it is invoked.
Then I close my browser window.
How Session behaves ? How is it created, destroyed in this case?
if this servlet is "detached" from all the web app, and gets parameters only using post & get, so it does not need Session at all, should one use Session.invalidate at the end of doGet(), doPost() ?
The servlet container usually keeps track of session using either (1) a HTTP cookie or (2) adding an extra parameter jsessionid in each URL.
When a user access this site and no session exist already, a new one is created for him, including the corresponding HttpSession. If necessary, the user might be redirected to a login page.
The effect of Session.invalidate will basically be: "Discard the current session for this user. If he access another page on the site, a new session will be created".
So far I know, session invalidation is used typically to implement logout feature.
I wouldn't call Session.invalidate in your "detached" servlet, it will interfere with the other pages. Basically, you don't care about the session in your servlet, you don't use it anyway.
Maybe have also a look at this question about disabling the session.
Then I close my browser window.
How Session behaves ? How is it created, destroyed in this case?
Are you asking what happens if the browser is closed even before the response is received back at the client?
In such a case, a Session will still be created on the server. It will persist for a specified time period and then expire.
The next request from your browser will create a new Session.
See more on this here: http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpSession.html
Regarding session.invalidate - ewernli has already answered.

Best option for Session management in Java

Best way managing session in Java. I heard that cookies are not reliable option for this as they gets stored into browser and can be accessed later on? Is this correct? If possible please come up with the answers with the coding example.
Which is the best among:
URL Rewriting: Server will add an additional parameter at the end of URL link
Hidden parameter in Form: server will add an additional parameter at every form in HTML
cookie: Server will ask browser to maintain a cookie.
The session management (client identification, cookie handling, saving session scoped data and so on) is basically already done by the appserver itself. You don't need to worry about it at all. You can just set/get Java objects in the session by HttpSession#setAttribute() and #getAttribute(). Only thing what you really need to take care of is the URL rewriting for the case that the client doesn't support cookies. It will then append a jsessionid identifier to the URL. In the JSP you can use the JSTL's c:url for this. In the Servlet you can use HttpServletResponse#encodeURL() for this. This way the server can identify the client by reading the new request URL.
Your new question shall probably be "But how are cookies related to this? How does the server do it all?". Well, the answer is this: if the server receives a request from a client and the server side code (your code) is trying to get the HttpSession by HttpServletRequest#getSession() while there's no one created yet (first request in a fresh session), the server will create a new one itself. The server will generate a long, unique and hard-to-guess ID (the one which you can get by HttpSession#getId()) and set this ID as a value of the cookie with the name jsessionid. Under the hood the server uses HttpServletResponse#addCookie() for this. Finally the server will store all sessions in some kind of Map with the session ID as key and the HttpSession as value.
According to the HTTP cookie spec the client is required to send the same cookies back in the headers of the subsequent request. Under the hood the server will search for the jsessionid cookie by HttpServletRequest#getCookies() and determine its value. This way the server is able to obtain the associated HttpSession and give it back by every call on HttpServletRequest#getSession().
To the point: the only thing which is stored in the client side is the session ID (in flavor of a cookie) and the HttpSession object (including all of its attributes) is stored in the server side (in Java's memory). You don't need to worry about session management youself and you also don't need to worry about the security.
See also:
Authenticating the username, password by using filters in Java (contacting with database)
How to redirect to Login page when Session is expired in Java web application?
How to implement "Stay Logged In" when user login in to the web application
All Java web frameworks support cookies or URL-encoded session IDs. They will chose the correct approach automatically, so there is nothing you need to do. Just request the session object from your container and it will handle the details.
[EDIT] There are two options: Cookies and a special URL. There are problems with both approaches. For example, if you encode the session in an URL, people can try to pass the session on (by putting the URL into a mail, for example). If you want to understand this, read a couple of articles about security and build app servers. Otherwise: Your Java app server will do the right thing for you. Don't think about it.
The cookie just stores the session ID, this ID is useless once the session has expired.
Servlet specification defines the API for accessing/setting session data in standard J2EE application. Also it defines that session data is stored on the server-side and nothing is transferred to the client except the session identifier. There are 2 mechanisms how session id is transferred:
1) request URL e.g. jessionid=....
2) cookie
Mechanism is determined automatically based on client capabilities.
EDIT. There is no best option, there is servlet specification that defines the way.
Http is a stateless, client-side pull only protocol.
To implement a stateful conversation over it, Java EE Web Server need to hide some information (which is sessionid) in client-side and the mechanism it can use should follow HTTP and HTML spec.
There are three ways to accomplish this goal:
URL Rewriting: Server will add an additional parameter at the end of URL link.
Hidden parameter in Form: server will add an additional parameter at every form in HTML.
cookie: Server will ask browser to maintain a cookie.
Basically, modern web server will have a "filter" to choose which way to use automatically.
So if Server detected that browser already turn off cookie support, it will switch to other ways.
2 important questions:
Which web technology are you using? JSF, Struts, SpringMVC or just plain servlets/JSPs.
Servlets/JSPs already give you the session support you need. JSP Example: Hello, <%= session.getAttribute( "theName" ) %>
I really don't think you have something to worry about cookies, since the data is stored safely in the server and handeling the cookie is done automaticlly.
Is your application installed on a single server?
If YES than you have no problem, use the servlet session option.
if NO than you gotta find another way to do this. Like using a sticky session, or maybe parse the entire session object in the requests/responses as a field. This option indeed requires you to take security measures.

Categories

Resources