Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleting a cookie using java

i have written the next code:

public void delete(MyType instance) {
        List<MyType> myList = this.getAll();

        Cookie[] cookies = request.getCookies();
        List<Cookie> cookieList = new ArrayList<Cookie>();
        cookieList = Arrays.asList(cookies);
        for(Cookie cookie:cookieList) {
            if(Long.valueOf(cookie.getValue()) == instance.getId()) {
                cookieList.remove(cookie);
            }
        }
        myList.remove(instance);
        cookies = (Cookie[]) cookieList.toArray();
}

the issue is next: when i delete the cookie from the cookielist, how i can put the updated cookielist (without deleted cookie) back to the client? request or response don't have any *.setCookies(); methods. or cookies will update automatically? best regards.

like image 731
John Smith Avatar asked Jun 19 '12 14:06

John Smith


People also ask

How can you delete a cookie in Java?

Full Stack Java developer - Java + JSP + Restful WS + Spring Read an already existing cookie and store it in Cookie object. Set cookie age as zero using the setMaxAge() method to delete an existing cookie. Add this cookie back into the response header.

How do I delete cookies in eclipse?

Open Eclipse and navigate to the Window > Preferences. Scroll down the left-hand panel in the Preferences window and click the Remote Systems drop-down root menu. 3. Click the Clear Cached Files button in the File Cache window.


1 Answers

You need to set the very same cookie with a null value and a max age of 0 (and the same path, if you have set a custom one) back on the response by HttpServletResponse#addCookie().

cookie.setValue(null);
cookie.setMaxAge(0);
cookie.setPath(theSamePathAsYouUsedBeforeIfAny);
response.addCookie(cookie);

Unrelated to the concrete problem, you do not need massage the array to a list and back at all. The enhanced for loop works on arrays as good. Also, using == to compare Long values would only work for values between -128 and 127. You need equals() instead. So all in all, the method could look like this:

public void delete(MyType instance) {
    Cookie[] cookies = request.getCookies();

    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (Long.valueOf(cookie.getValue()).equals(instance.getId())) {
                cookie.setValue(null);
                cookie.setMaxAge(0);
                cookie.setPath(theSamePathAsYouUsedBeforeIfAny);
                response.addCookie(cookie);
            }
        }
    }
}

By the way, it's scary to see request and response being instance variables of some class. Are you sure that the particular class is threadsafe? To understand servlets and threadsafety, you may find this answer helpful: How do servlets work? Instantiation, sessions, shared variables and multithreading.

like image 81
BalusC Avatar answered Sep 25 '22 21:09

BalusC