Cookie cookie = new Cookie("name","abc"); //new Cookie(String,String)
cookie.setMaxAge(1000);
//in seconds, default if not set: cleaned when browser closed
response.addCookie(cookie); //remember to call addCookie
Get cookie
//Have to get all cookies as Array, then loop through each of them
Cookie cookies[] = request.getCookies(); //return null if none cookies
for(int i=0;i<cookies.length;i++){
Cookie cookie = cookies[i];
cookie.getName();
cookie.getValue();
cookie.getMaxAge();
}
- Multiple browsers can share the same cookie
- If set the same key word, the old value will be replaced
- Every cookie can have their own life length
- All cookie from the same webapp will store in one single file on client hard drive, with timestamp
- 20 most cookies a webapp can save to browser, each cookie have 4k max space
- a browser can save 300 most cookies
Cookie life cycle
- Cookie by default, will be destroyed when browser closed
- setMaxAge(1000) can set length of life time for cookie
- setMaxAge(0) destroy cookie
- setMaxAge(-1000) cookie will destroy when browser closed
Cookie with Different Character set
Saving
String val = java.net.URLEncoder.encode("中国字","utf-8");
Cookie cookie = new Cookie("name",val);
Getting
String val = java.net.URLDecoder.decode(cookie.getValue(),"utf-8");
No comments:
Post a Comment