1/13/2009

Cookie

javax.servlet.http.Cookie

A client connects to a server.

The server adds a cookie to the response.

The client saves the cookie.

The client connects to the server again.

The server identifies the client by the cookie.

Add a cookie to the response.
HttpServletResponse#addCookie
e.g.
Cookie cook= new Cookie(name, value);
cok.setMaxAge(60*60*24*180);
res.addCookie(cok);

Get Cookie objects
HttpServletRequest#getCookies
All cookies the client sends with this request are stored in the array.

Encoding
The argument "value" of the Cookie can be encoded by using java.net.URLEncoder#encode(String s, String enc).
In the requested resource, use java.net.URLDecoder#decode(String s, String enc) to decode it.

<Sample>
    Cookie cook= new Cookie("message",
    URLEncoder.encode("こんにちは", "utf-8"));

<Sample>
    String str = null;
    Cookie[] cook= request.getCookies();
    if (cook!= null) {
        for (int i = 0; i < cok.length; i++) {
            if (cok[i].getName().equals("message")) {
                str = URLDecoder.decode(cok[i].getValue(), "utf-8");
                break;
            }
        }
    }