您的位置:首页 > 其它

Cookie

2016-06-12 23:57 232 查看
Cookie是什么?
它是浏览器与服务器回话过程中产生的数据,保存在浏览器上。当需要时再发送给服务器端使用。
底层实现:
cookies:请求头-发送到服务器端 request.getCookies();
set-cookie:响应头-由服务器端进行设置 response.setCookie(cookie实例);
Cookie常用属性:name 、value、path、MaxAge、domain、comment、version、secure
服务器端Cookie操作:
【1】如何得到Cookie?
Cookie []cookies = request.getCookies();
for(int i=0; cookies!=null && i<cookies.length(); i++){
Cookie c = cookies[i];
if("myCookieTime".equals(c.getName())){
String time = c.getValue();
Date date = new Date(Long.parseLong(time));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
String result = sdf.format(date);
response.getWriter().write(result);
}
}
【2】如何将Cookie值设置到浏览器中
Cookie cookieTime = new Cookie("myCookieTime",System.currentTimeMillis());
cookieTime.setMaxAge(Integer.MAX_VALUE);
response.setCookie();

Cookie对象:
构造方法: Cookie cookie = new Cookie(String name, String value);
普通方法:
cookie.clone();
cookie.getName();
cookie.getValue();
cookie.getPath();
cookie.getMaxAge();
cookie.getDomain();
cookie.getVersion();
cookie.getComment();
cookie.getSecure();

cookie.setName();
cookie.setValue();
cookie.setPath();
cookie.setMaxAge();
cookie.setPath();
cookie.setDomain();
cookie.setVersion();
cookie.setComment();
cookie.setSecure();

从request对象中得到cookie信息
Cookie cookies[] = request.getCookies(); //获取请求头中Cookie信息
for(int i=0; cookies!=null && i<cookies.length(); i++){
Cookie cookie = cookies[i];
if("myCookieTime".equals(cookie.getName())){
String time = cookie.getValue();
Date date = new Date(Long.parseLong(time));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
String value = sdf.format(date);
response.getWriter().write(value);
}
}

使用response对象将cookie值设置到浏览器中
Cookie cookie = new Cookie("myCookieTime",System.currentTimeMillis+"");
cookie.setMaxAge(Integer.MAX_VALUE);
response.addCookie(cookie实例); //将Cookie实例信息设置到浏览器中:响应头信息set-cookie

//删除指定Name的cookie
Cookie cookie = new Cookie("myCookieTime","");
cookie.setMaxAge(0); //将MaxAge设为0,即为删除
response.setCookie(cookie);

服务器写回给浏览器的cookie信息:mycookieTie140426635089764localhost/day09_00_cookies/servlet
name+value+domain+path
浏览器是不是要把本地的cookie信息发送给服务器,是由浏览器做决定:name+domain+path来决定

本文出自 “sharemi” 博客,请务必保留此出处http://sharemi.blog.51cto.com/11703359/1788498
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: