Java, Session Handling

How to delete cookies in servlet in Java?

Here is how you delete cookies in servlet in Java:


    public void invalidateSession() {

        // Request object to fetch the cookies
        HttpServletRequest request = this.getThreadLocalRequest();

        // Response object to delete the cookies
        HttpServletResponse response = this.getThreadLocalResponse();
        response.setContentType("text/html");

        Cookie[] cookies = request.getCookies();

        // Delete all the cookies
        if (cookies != null) {

            for (int i = 0; i < cookies.length; i++) {

                Cookie cookie = cookies[i];
                cookies[i].setValue(null);
                cookies[i].setMaxAge(0);
                response.addCookie(cookie);
            }
        }
    }

Note: A negative value (in setMaxAge() method) means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.

Advertisements

3 thoughts on “How to delete cookies in servlet in Java?

    1. Thanks for pointing it out! Though my code works, your suggestion makes more sense since we have a local variable ‘cookie’. Must be an oversight on my part. 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s