Cookie
Cookie是web服务器通过浏览器保存在WWW用户端硬盘上的一个文本文件,这个文本文件中包含了文本信息。
是以key/value来保存。
解决浏览器用户与web服务器之间的无状态通信。
cookie的典型应用。
1,实现“记住我”功能。
2,定制个性化页面。
3,记录用户访问的动作。
cookie编程
1生产Cookie对象
java.util.Date date=new java.util.Date();
Cookie c=new Cookie("lastVisited",date.toString());//都只能是String类型。
可以设置有效期,
c.setMaxAge(60*60*24);
可是设定路径和域名。
setPath();
setDmain();
response.addCookie(c);
2读取Cookie
Cookie[] cookies=request.getCookies();
Cookie c=null;
if(cookies!=null){
for(int i=0;i{
c=cookies[i];
System.out.println(c.getName);c.getvalue()
}
}
删除Cookie 就是设定有效时间为0,然后response发过去。
使用Cookie的注意事项
大小和数量有限制。
只能是英文字符和数字。
信息没有加密。
还有浏览器的用户可以设定不使用Cookie,
session 和Cookie的区别
A session as you probably mean it is a server-side object which stores state. You use it in servlets to store and retrieve data. You keep hearing people saying HTTP is a stateless protocol, right? They mean when you load a page, you're finished as far as the web server is concerned. If you reload a page, the new request isn't associated in any way with the previous one.
A cookie is a small piece of information a browser sends to a server with every request.
Most servlet containers use a cookie to identify a session.
1) The user's browser requests a servlet.
2) The servlet container creates a session.
3) The servlet gives the session a unique ID.
4) The servlet sets a cookie in the browser with this ID.
5) Let's say the servlet then store's the user's name in
the session.
5) The user requests another servlet on the same server.
As part of the request, the cookie with the session ID
is sent back to the server.
6) Since the servlet container is told which session to use,
it make it available again.
7) So servlet #2 can retrieve the user's name, since we
put it in the session, and say, "Hi, Bob."
阅读(556) | 评论(0) | 转发(0) |