checking session in servlet and jsp - java

In my web application i neet to check session already exist or not.
i want to check this in my servlet and in jsp also.
is there any way to check this.
Thanks

You can test it with HttpServletRequest#getSession(boolean create) with create=false. It will return null if not created yet.
HttpSession session = request.getSession(false);
if (session == null) {
// Session is not created.
} else {
// Session is already created.
}
If you actually want to create the session anyway if it doesn't exist, then just grab it and test the freshness using HttpSession#isNew():
HttpSession session = request.getSession();
if (session.isNew()) {
// Session is freshly created during this request.
} else {
// Session was already created during a previous request.
}
That was how you would do it in a Servlet. In a JSP you can only test the freshness with help of JSTL and EL. You can grab the session by PageContext#getSession() and then just call isNew() on it.
<c:if test="${pageContext.session.new}">
<p>Session is freshly created during this request.</p>
</c:if>
or
<p>Session is ${pageContext.session.new ? 'freshly' : 'already'} created.</p>

One way is to set a session id in the jsp and then check the same session id in the other jsp or servlet to check if it is alive or not.
HttpSession session = req.getSession();
session.getId();

Related

After response.sendRedirect(redirect) session becomes null

Here request is an object type which extends HttpServletRequest. This is the sequence of code.
HttpSession session;
session = request.getSession(false);
response.sendRedirect(redirect);
session = request.getSession(false);
In the first line, able to get the valid session value. But after 2nd statement sendRedirect execution. session object is becoming NULL in the 3rd statement.
For the redirected request to come back and attach to the same session, it needs a session ID, usually carried in a JSESSIONID (or another name) cookie or in the URL as a parameter.
This cookie or URL parameter should be added by the servlet container and you should not have to add it yourself.
If you do not see the cookie in your browser, and you are not attaching the JSESSIONID to the URL, then it is creating a new session with each request, and not attaching to the same session

How to determine Java Servlet / Spring session timeout and good practise

I noticed that the jsessionId will get sent across to the server so in the filter I could actually get the expired session id from the cookies.
Is it ok to put a filter logic like the following?
Cookie jsessionCookie = getSessionIdCookies(request);
Session session = request.getSession(false);
if (session == null || !(jsessionCookie.getValue().equals(session.getId())) {
//this should be a timeout handling
....
} else {
// normal moving forward
}
Since the session == null could also because of a new request (which can be filtered out by setting particular filter rules), can I more rely on !(jsessionCookie.getValue().equals(session.getId())?
Or even change the request.getSession(false) to request.getSession() and just always compare the cookie with the session id?
Is there a better management practice for session timeout management?
You can register a HttpSessionListener on the ServletContext to get notified when a session is invalidated.

Java HttpSession

Is HttpSession in java servlet is created only after
HttpSession s = request.getSession();
?
In my code I didn't write that, but when I use if (request.getSession(false) == null) ..., it doesn't work. Why?
A HttpSession is created when calling request.getSession().
But if you access a JSP by default it will automatically create a session.This behaviour can be disabled by using: <%# page session="false">
Are you using JSP?
Read JavaDocs, it says clearly:
This says, request.getSession()
Returns the current session associated with this request, or if the request does not have a session, creates one.
And the other variant request.getSession(isCreate)
Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
If create is false and the request has no valid HttpSession, this method returns null.
To make sure the session is properly maintained, you must call this method before the response is committed. If the container is using cookies to maintain session integrity and is asked to create a new session when the response is committed, an IllegalStateException is thrown.
Update
On a bit research, I have found that Session is not created unless request.getSession() is called somewhere. Since, The servlet container uses this interface to create a session between an HTTP client and an HTTP server. There are good chances that your Servlet container creates the Session for you by default.
refer:
Java Doc HttpSession
Discussion on JavaRaunch: is HttpSession created automatically?
But, to be safer side, use request.getSession() to get session, and use request.getSession(false) only when you need to verify if a session has already been created.
In addition to Nishant's answer note that session can be created implicitly by JSP pages unless you configured them not to create a session with <%# page session = "false" %>.
To make it complete:
session is not created, unless you call request.getSession(), in your servlet, use request.getSession(false) to get existing session without creating new session
if you use JSP page, session is automatically created for you - variable session - unless you specify <%# page session="false" %>
even if your session is created automatically, you can use session.isNew() to find out, if it has been newly created
Try to remove session cookies from browser and make another test. If it does not work then some other component is creating a new session before that call.

Ensure a new session every time the user connects to a Servlet

I've a JSP/Servlet Web App that consist of more than one servlet (and some JSPs)
I need to create an new HttpSession whenever the users access servlet A, knowing that, servlet A is the home page (i.e. he access it as the first servlet/page in the application).
So far so good, I can write the following code at the start of the servlet A:
HttpSession session = request.getSession(false);
if (session == null) {
logger.debug("starting new session...");
session = request.getSession();
// other stuff here
}
But the problem is, if the user didn't close his browser (even if he closes the tab - in Firefox for instance - the session will still be open), so when he try to open my site again, the last session will be re-used (in the range of session timeout of course), and this I don't need. I need that whenever he accesses Servlet A, he gets a brand new HttpSession.
But unfortunately, he may access this servlet twice per session based on some scenario!
It seems to me that you should not be using session for this purpose. Perhaps you can add a parameter to request (i.e. transaction id) and pass it around trough all your related requests, so when user would close page the transaction id would be gone. Then you can store any data associated with given transaction id in the http session or elsewhere and could also clean it after some time.
The spring framework has an abstraction called bean scope, which seem like a good fit for your scenario, so you can create a custom scope for your transaction (or user's session) and store all the data in some bean scoped with such custom scope.
You should store some information (attribute) in the session that it's been used. And if it has been, invalidate
HttpSession session = request.getSession();
Object isOld = session.getAttribute( "isOld" );
if ( isOld != null )
{
session.invalidate( );
// Recreate session
session = request.getSession( );
}
session.setAttribute( "isOld", new Object( ) );

Session Problem

The
HttpSession session = request.getSession(true);
and
HttpSession session = request.getSession();
both creates a new session if there is none present.
My problem is that i want to invalidate() the session if its allready present and then create a new one.
I that possible ..i mean is there any way out to achieve this..??
How about this?
HttpSession session = request.getSession(false); // Will not create a new session.
if(session!=null)
{
session.invalidate();
}
session = request.getSession(true);
first kill your old session
session.invalidate();
and after that reopen it with
HttpSession session = request.getSession(true);
dont work?
First do a session.invalidate(); and if necessary then do a response.sendRedirect("url"); to an url where in you can just do request.getSession(); to get a new session.
Note that this approach is not guaranteed to work in a JSP file, simply because the response is in most cases already committed (so that the container cannot set the new value of the jsessionid cookie in the response header). You really need to do this in a Servlet or Filter.
That said, why exactly do you want to invalidate the session and then immediately get a new session all in the same request? This sounds like a workaround for a certain problem for which there may be better solutions.

Categories