简体   繁体   English

使用java删除cookie

[英]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? 问题是下一个:当我从cookielist中删除cookie时,我如何将更新的cookielist(没有删除的cookie)放回客户端? request or response don't have any *.setCookies(); 请求或响应没有任何*.setCookies(); methods. 方法。 or cookies will update automatically? 或cookie会自动更新? best regards. 最好的祝福。

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() . 您需要通过HttpServletResponse#addCookie()将响应设置为具有null值且最大年龄为0相同cookie(以及相同路径,如果已设置自定义路径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. 增强的for循环适用于数组。 Also, using == to compare Long values would only work for values between -128 and 127. You need equals() instead. 此外,使用==来比较Long值仅适用于介于-128和127之间的值。您需要使用equals() 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. 顺便说一下,看到requestresponse是某个类的实例变量是很可怕的。 Are you sure that the particular class is threadsafe? 你确定特定的类是线程安全的吗? To understand servlets and threadsafety, you may find this answer helpful: How do servlets work? 要了解servlet和线程安全性,您可能会发现这个答案很有用: servlet如何工作? Instantiation, sessions, shared variables and multithreading . 实例化,会话,共享变量和多线程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM