在Java Servlet中,如何更改现有cookie的值?

Zub*_*air 30 java cookies servlets

在Java Servlet中,如何更改现有cookie的值?有一个addCookie方法,但在HttpServletResponse中没有deleteCookie或editCookie

Bal*_*usC 44

那些确实不存在.只需自己创建实用程序方法即可.特别是获得所需的cookie非常臃肿.例如

public final class Servlets {

    private Servlets() {}

    public static Cookie getCookie(HttpServletRequest request, String name) {
        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if (cookie.getName().equals(name)) {
                    return cookie;
                }
            }
        }

        return null;
    }

}
Run Code Online (Sandbox Code Playgroud)

要编辑cookie,请设置其值,然后将其添加到响应中:

Cookie cookie = Servlets.getCookie(request, "foo");

if (cookie != null) {
    cookie.setValue(newValue);
    response.addCookie(cookie);
}
Run Code Online (Sandbox Code Playgroud)

如果必要,还可以设置maxage,path和domain(如果它们与默认值不同).客户端即不发送此信息.

要删除cookie,请将最大年龄设置为0(最好也是值null):

Cookie cookie = Servlets.getCookie(request, "foo");

if (cookie != null) {
    cookie.setMaxAge(0);
    cookie.setValue(null);
    response.addCookie(cookie);
}
Run Code Online (Sandbox Code Playgroud)

必要时设置路径和域,如果它们与默认值不同.客户端即不发送此信息.


Jam*_*ard 5

以下是kodejava的示例:

 public class ReadCookieExample extends HttpServlet {
 protected void doPost(HttpServletRequest request, HttpServletResponse   response)         throws    ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter writer = response.getWriter();

    Cookie[] cookies = request.getCookies();
    for (int i = 0; i < cookies.length; i++) {
        writer.println("Name: " + cookies[i].getName() + "; Value: "                    +                   cookies[i].getValue());            
    }
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws    ServletException, IOException {
    doPost(request, response);
}
Run Code Online (Sandbox Code Playgroud)

}

这将得到cookie列表,得到你想要的那个,而不是打印出值,做类似的事情:

 cookie.setValue(String.valueOf(<new Value>));  
 cookie.setMaxAge(60*60*24*365);   
 cookie.setPath("/");   
 response.addCookie(cookie);  etc...
Run Code Online (Sandbox Code Playgroud)

HTH,

詹姆士