[wp-night-mode-button]

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:

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.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.