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
Related
I'm developing Java Servlets. At the point of checking whether a user is logged in, I want to check if the HTTP request has a valid session. For checking that, I have 2 possibilities:
(1)
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session != null) {
// user is logged in
...
}
}
Since I pass false as an argument, there is no new session created if there is no valid session existing already, and the function returns null, for what I can check.
Or I do:
(2)
if (request.isRequestedSessionIdValid()) {
// user is logged in
...
}
Is there any difference, any advantage/disadvantage? Or do both functions do more or less the same?
Form Javadoc
isRequestedSessionIdValid
boolean isRequestedSessionIdValid()
Checks whether the requested session ID is still valid.
If the client did not specify any session ID, this method returns false.
Returns:
true if this request has an id for a valid session in the current session context; false otherwise
So in sense both are same. But what you need to be aware of is request.getSession(false) will be null only in case of first request to the container. After the first request container creates a session and sends Jsessionid cookie along with response , so that it can track subsequent requests from the same browser. So in your case instead of checking if session is null or not, you should store a session attribute "is_logged_in"=true and check for this attribute as well if session is not null.
Based on the wording of the JavaDoc, it seems like there would be a distinction: if a valid session has already been created (from a prior call to request.getSession(true)), then the requested session ID will not be valid, but request.getSession(false) will have a valid (non-null) session to return. I haven't tested this theory.
I'm using a URL with a jsessionid, eg.
http://localhost:8080/myservlet;jsessionid=123
Yet whenever I read the session ID in the HttpServletRequest the value is never 123, but instead a generated session ID, eg. B663A96D3FBC84B4A427C0810EAB9073.
Why is my jsessionid being ignored?
That's because you specified a session ID for which no concrete HttpSession object exist in server's memory. In other words, the given session ID is unknown/invalid. You need to specify a session ID which refers a valid and existing HttpSession object in server's memory.
Assuming that you do have a valid HttpSession with ID B663A96D3FBC84B4A427C0810EAB9073 currently in server's memory, then the following link will work and give the enduser access to exactly that HttpSession:
http://localhost:8080/myservlet;jsessionid=B663A96D3FBC84B4A427C0810EAB9073
My guess would be that most application servers these days default to using cookies for session tracking, not URL rewriting. So if your request contains both a session cookie and a JSESSIONID in the URL, it will probably use the one from the cookie. Check the documentation of your appserver for how to configure this.
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.
Hi just want to confirm when a session is expired in a webapp based on servlet.
The following session id will be available until the session is garbage collected, is that correct?
httpServletRequest.getRequestedSessionId()
Thanks,
C
if the session got expired, then at that point the session will be garbage collected and
httpServletRequest.getRequestedSessionId() will return new value when that method is called.
please check below url
http://download.oracle.com/docs/cd/E17802_01/products/products/servlet/2.1/api/javax.servlet.http.HttpServletRequest.html#getRequestedSessionId%28%29
When a session is expired getRequestedSessionId() return id new session which will be created when you call this method
To check if session is timed-out (in invalid state) check isRequestedSessionIdValid
From JavaDoc
getRequestedSessionId
public abstract String
getRequestedSessionId()
Gets the session id specified with this request. This may differ from the
actual session id. For example, if the
request specified an id for an invalid
session, then this will get a new
session with a new id.
Returns:
the session id specified by this request, or null if the request
did not specify a session id
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( ) );