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:
If you use below code to get the session:
HttpSession session = request.getSession();
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.
HttpSession session = request.getSession(false);
if (session == null) {
// No session present, you can create yourself
session = request.getSession();
} else {
// Already created.
}
If you still want to use request.getSession(), you can use session.isNew() method to check if it is newly created or not.
HttpSession session = request.getSession();
if (session.isNew()) {
// Just created.
} else {
// Already created.
}
I hope, it will help you to check if HTTP session exists or not.