I am facing very strange problem while developing JavaEE WEB Application.
Even after invalidating the HttpSession using session.invalidate();, I am not getting session null. There is a case where I have one statement in execution like below after invalidating session.
if (null != session && null != session.getAttribute("loginToken")){
//do something
}
I am not getting session null here so second condition will try to execute. And hence session is not null, so I am getting IllegalStateException - session is already invalidated. But why session is not null after invalidating it?? :(
Calling session.invalidate() removes the session from the registry. Calling getSession(false) afterwards will return null (note that getSession() or getSession(true) will create a new session in this case, see HttpServletRequest API). Calling invalidate() will also remove all session attributes bound to the session. However if your code still has references to the session or any of its attributes then these will still be accessible:
// create session if none exists (default) and obtain reference
HttpSession session = request.getSession();
// add a session attribute
session.setAttribute("lollypop", "it's my party");
// obtain reference to session attribute
Object lollypop = session.getAttribute("lollypop");
// print session ID and attribute
System.out.println(session.getId());
System.out.println(lollypop);
session.invalidate();
// session invalidated but reference to it still exists
if (session == null) {
System.out.println("This will never happen!");
}
// print ID from invalidated session and previously obtained attribute (will be same as before)
System.out.println(session.getId());
System.out.println(lollypop);
// print 'null' (create=false makes sure no new session is created)
System.out.println(request.getSession(false));
Example output:
1k47acjdelzeinpcbtczf2o9t
it's my party
1k47acjdelzeinpcbtczf2o9t
it's my party
null
So far for the explanation. To solve your problem you should do:
HttpSession existingSession = request.getSession(false);
if (existingSession != null && existingSession.getAttribute("loginToken") != null){
//do something
}
The invalidate method does the following (from API):
Invalidates this session then unbinds any objects bound to it.
It says nothing about the HttpSession-object itself, but invalidates the session's variables. If you call a method of a class, it is impossible for the object to be null after that method call. If your session should be null afterwards, the method must include a line that looks something like: this = null; which would not be possible. Throwing an exception for an invalidated session is the prefered way to do it.
Try passing false as the parameter to the getSession(boolean) . This will give back a session if it exists or else it will return null.
HttpSession session = request.getSession(false);
if(session==null || !request.isRequestedSessionIdValid() )
{
//comes here when session is invalid.
}
Related
I am trying to invalidate the existing session and trying to create an new session for application after successful login/process. But JSESSIONID remains same before and after invalidating the session.
but prevsession.getId() and session.getId() is same.
HttpSession prevsession = request.getSession(false);
if (prevsession != null)
{
prevsession.invalidate();
}
HttpSession session = request.getSession(true);
I expecting here is, request.getSession(true) will create an new JSESSIONID after invalidating session.
Any help is much appreciated.
This is not a defect and could be server container behavior where session IDs are used, sessions still remain unique.
I have the following piece of code in my program and I am running SonarQube 5 for code quality check on it after integrating it with Maven.
However, Sonar is asking to Remove this useless assignment to local variable "session".
#RequestMapping(value = "/logoff", method = RequestMethod.GET)
public String getLogoffPage(HttpServletRequest request, HttpServletResponse response) {
logger.info(" Before Log Offf........ " + request.getSession().getId() );
HttpSession session =request.getSession(true);
request.getSession().invalidate();
myApplication.logout();
SecurityContextHolder.clearContext();
session=null;
return "login";
}
Under the assumption that the question is "why":
What do you actually do with session? Nothing.
HttpSession session =request.getSession(true); // session assigned
request.getSession().invalidate(); // session NOT used
myApplication.logout();
SecurityContextHolder.clearContext();
session=null; // session re-assigned
Perhaps you meant this?
HttpSession session =request.getSession(true);
session.invalidate();
myApplication.logout();
SecurityContextHolder.clearContext();
BTW, I've dropped session = null since there's no reason in Java (C would be another matter) to do that.
Of course, the code could be even cleaner:
request.getSession().invalidate();
myApplication.logout();
SecurityContextHolder.clearContext();
This variable is local and so when you reach the return statement it won't be accessible. As it is not read after the assignement the variable is considered Dead.
If you assign anything to a local variable and do not make use of it this is a useless instruction and thus should be removed.
Setting the variable to null is pretty much useless and in fact may be preventing the JVM to work on some optimization.
/****NOTE****/
in WEB.XML file I am setting session timeout property,
so may be session is expired.
/************/
I am using HttpSession object to manage session
HttpSesion session = myPersonalMethodThatReturnHttpSessionObject();
//I am using Eclipse and it provide me following details in Debug view I put Image Below
//so how can i get value of isValid field or method so here i can put in if condition
if(session != null)
{
//removing attributes from session
}
/*************************************More Description*******************************************/
My Problem is...
note1 --> session timeout is 30 min.
Step1 some one login my web apllication
Step2 session is created.
Step3 if user close web application without signout
Step4 all session attribute is there
Step5 if another user try to login.
Step6 I try to remove all session attribute and store new attribute value.
Step7 Above functionality work properly but, while session is invalidate can't remove session attribute so i need to put condition in if session is valid that remove attribute else do nothing so I need to check session is valod or not.
Since you are seeing isValid=false , I guess your session has become invalid/timedout.
You should be calling HttpSession session = request.getSession(true); or HttpSession session = request.getSession(); to always get the valid session.
The method request.getSession(true) will ensure that it will create a new session if the current session is invalid. If the current session is valid, it will return the same.
The method request.getSession(); by default calls request.getSession(true);.
Based on your update, your login process should be as follows:
HttpSession session = request.getSession(false); // returns null if no session or session is invalid
if(session != null) {
// you have old session
session.invalidate(); // invalidate session - this will remove any old attrs hold in the session
}
// create new session
session = request.getSession(); // creates new empty session
....
You cannot get the isValid field directly. The request.getSession(false) is using it and will return null, if current session is invalid. If session is already invalid you don't have to remove attributes, since they already have been removed and session is inaccessible any more.
you should create an concrete class which implement javax.servlet.http.HttpSessionListener and add your code into its two callback methods:
public interface HttpSessionListener extends java.util.EventListener {
void sessionCreated(javax.servlet.http.HttpSessionEvent httpSessionEvent);
void sessionDestroyed(javax.servlet.http.HttpSessionEvent httpSessionEvent);
}
remember to register your listener in web.xml!
You create session with HttpServletRequest object as follows.
HttpSession session = httpServletRequest.getSession();
This will give you new session if one is not already created or return existing session object.
somewhere in you method myPersonalMethodThatReturnHttpSessionObject() add the following line
HttpSession session = request.getSession(false);
This will help you to find valid session.
What do these calls actually mean in terms of session?
System.out.println("print1: "+request.getSession().getId());
System.out.println("print2: "+request.getSession(false));
OUTPUT
print1: D94146A347D95563186EB7525726336B
print2: org.apache.catalina.session.StandardSessionFacade#d52411
HttpSession session = request.getSession(); Inside the service method we ask for the session and every thing gets automatically, like the creation of the HttpSession object. There is no need to generate the unique session id. There is no need to make a new Cookie object. Everything happens automatically behind the scenes.
As soon as call the method getSession() of the request object a new object of the session gets created by the container and a unique session id generated to maintain the session. This session id is transmitted back to the response object so that whenever the client makes any request then it should also attach the session id with the requsest object so that the container can identify the session.
request.getSession(false) : This method will check whether Session already existed for the request or not. If it existed then it will return the already existed Session. If Session is not already existed for this request then this method will return NULL, that means this method says that the request does not have a Session previously.
In short-
request.getSession().getId() - returns a string containing the unique identifier assigned to this session. The identifier is assigned by the servlet container and is implementation dependent.
request.getSession(false) - return session object or null if there's no current session.
First line will return the "session id" on server.
The second line will return session object. So what will be printed on system.out would be request.getSession(false).toString();
The default implementation of toString returns the "object id". Object id in terms of session is not the same as session id. Session could be serialized and replicated across the cluster so on each node of the cluster on each JVM it may have it's own object id (but should have same session id).
Calling get session with boolean is explained here:
http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getSession(boolean)
request.getSession()
This method will check for the existing session;if exist its return otherwise create a new session for the request.
request.getSession().getId();
This will return the unique identifier for that session.
request.getSession(false);
This method takes the boolean value.This method check whether there is an existing session present for that user(request);if exist it return that session otherwise it return null i.e it won't create new session.
Just to add more information for session.
request.getSession(true);
This method checks for the existing current session for that user(request) and if the session exist it will return that session or otherwise it create new session for that user.
request.getSession() works like request.getSession(true)
Reference :
http://docs.oracle.com/javaee/1.4/api/javax/servlet/http/HttpServletRequest.html#getSession%28boolean%29
request.getSession().getId()
Returs the id of the session.
Request.getsession(false) returns the already existing session object. It wont return anything i.e. Will return null , if session does not exist. Whereas with true parameter it will create a new session object and return it if no session exists
request.getSession().getId();
Will return unique string id assigned to already started session. Generation of id is vendor specific like apache, jboss etc.
request.getSession(false);
It will return session object associated to particular request if session object is associated it will be returned or it will return null if its is not started by server.
request.getSession().getId();
this will return the id of the an existing session.
Request.getsession(false)
it will return the session if it exists, or it will return null otherwise.
and Request.getsession(false) means : give me the session if it exists, otherwise do not create a new instance (and thus return null).
request.getSession().getId();
returns the unique identifier assigned to this session. And It has return type of String.
request.getSession(false)
returns the HttpSession object if it already exists else return null.
I'm new to jsf and I've read that a session can be destroyed
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
fc.getExternalContext().getSessionMap().clear();
session.invalidate();
My problem ist, after doing that the session is still active, with the following bean :
com.sun.faces.renderkit.ServerSideStateHelper.LogicalViewMap
Do you have an idea?
That's just a new session. To test it yourself, check the value of HttpSession#getId() during the request before and after invalidate. It should be different.
Unrelated to the concrete question, clearing the session map is unnecessary whenever you call invalidate(). The session map will be trashed anyway. Also note that getSession(false) can potentially return null and you'd like to add an extra check to avoid NullPointerException. Or just use getSession(true) instead.