Removing cookie with java

I wrote the following 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 problem is this: when I delete a cookie from a cookielist, how can I put the updated cookielist (without deleted cookies) back to the client? The request or response has no methods *.setCookies();. or will cookies be updated automatically? with best regards.

+5
source share
1 answer

You need to set the same cookie with the value nulland the maximum age 0(and in the same way if you set a custom one) back to the answer HttpServletResponse#addCookie().

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

, . . , == Long -128 127. equals(). , :

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);
            }
        }
    }
}

, , request response . , ? , : ? , , .

+15

All Articles