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.
If you use below code to get the session:
1 2 3 |
HttpSession session = request.getSession(); |
1 2 3 4 5 6 7 8 9 |
HttpSession session = request.getSession(false); if (session == null) { // No session present, you can create yourself session = request.getSession(); } else { // Already created. } |
1 2 3 4 5 6 7 8 |
HttpSession session = request.getSession(); if (session.isNew()) { // Just created. } else { // Already created. } |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.