我们设想,在一个购物场景,客户端向服务器发送购买某件商品的请求,服务器跳转到下一个页面后,它是如何知道你要购买的是哪样产品呢?
cookie在这帮了大忙。
五点特征:
- 是服务器向客户端写入的内容
如果设置了生存周期,会写到电脑文件中;如果没有,会写到内存,窗口关闭就会消失。 - 仅允许写入文本内容(防止流氓软件)
- client端可以禁止写入cookie
- 服务器只能拿到自己webapp写入的东西
-
服务器对不同的客户端有编号区分
两个小例子理解cookie基本用法
- SetCookie
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class SetCookie extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
for (int i = 0; i < 3; i++) {
Cookie cookie = new Cookie("Session-cookie"+i,"Cookie-Value-S"+ i);//设置cookie的名字和value
resp.addCookie(cookie);//服务器回复的时候添加cookie
cookie = new Cookie("Persistent-cookie-"+i,"Cookie-Value-S"+i);
cookie.setMaxAge(3600);//设置生命周期为1小时
resp.addCookie(cookie);
}
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
String title = "Setting Cookies";
out.println(
"<html><head><title>设置cookie</title></head>"
+"<body>"
+title+"</H1>\n"
+ "there are six cookies associated with this page.\n"
+"<A HREF= \"ShowCookies\">\n"+
"<code>ShowCookies</code> servlet</a>\n"
+"</body>\n</html>"
);
}
}
- ShowCookies
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class ShowCookies extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
out.println("<html>\n<body>\n<table>\n");
Cookie[] cookies = req.getCookies();//getcookie是服务器从客户端读取cookie中内容
out.println(cookies.length);
if (cookies != null){
Cookie cookie;
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[I];
out.println("<tr>\n"+
"<td>" + cookie.getName()+"</td>\n"+
"<td>" + cookie.getValue()+"\n 什么呀"+"</td></tr>\n");
}
}
out.println("</table></body></html>");
}
}
注意:
- 一个servlet/jsp设置的cookie能够被同一个路径下或者子路径下面是servlet/jsp可以读到(这里的路径是指URL,路径不等于真实文件路径)
- 上面的小实验还说明:cookie有两种,属于窗口的和属于文本的