Java, Session Handling

How to get cookie value in servlet in Java?

In this example we are retrieving value of the cookie(APP_USER_NAME) we created in last post. If you are looking for how to create cookies in Java, please refer this post.

    public String retrieveCookieValue() {

    	HttpServletRequest request = this.getThreadLocalRequest();
    	Cookie[] cookies = request.getCookies();

    	String cookieValue = null;

    	// Get cookie value
    	if (cookies != null) {

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

    			if (cookies[i].getName().equals("APP_USER_NAME")) {

    				cookieValue = cookies[i].getValue();
    			}
    		}
    	}
    	return cookieValue;
    }

If you are looking for how to delete cookies in servlet in Java, please refer to this post.

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.