How to check if session exists or not in java

In this post, we will see how to check if HTTP session exists or not in java.  Sometimes you need to check if session already exists or not and based on that perform some operations.
If you use below code to get the session:

You will never get above session object as null because request.getSession() will always give you session object, so you can use request.getSession(false) code to get session and if session does not exist, it will return null.

If you still want to use request.getSession(), you can use session.isNew() method to check if it is newly created or not.

I hope, it will help you to check if HTTP session exists or not.

Add Comment