3.Cookie
-
从请求中拿到cookie信息
-
服务器响应给客户端cookie
Cookie[] cookies = req.getCookies();//获取cookie cookie.getName();//获取cookie中的key cookie.getValue();//获取cookie中的value Cookie cookie = new Cookie("lastLoginTime", "" + System.currentTimeMillis());//新建一个cookie cookie.setMaxAge(24*60*60);//设置cookie的有效期 resp.addCookie(cookie);//响应给客户端一个cookie
cookie:一般会保存在本地的用户目录下/AppData下
一个网站cookie是否存在上限?
- 一个cookie只能保存一个信息
- 一个web站点可以给浏览器发送多个cookie,每个web站点最多存放20个cookie( 不同的浏览器会有所不同)
- cookie大小有限制4kb
- 浏览器上限是300个cookie
删除cookie
- 不设置有效期,关闭浏览器,自动失效
- 设置有效期时间为0
演示代码
public class CookieDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决中文乱码
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
PrintWriter writer = resp.getWriter();
//cookie,服务器从客户端中获取
Cookie[] cookies = req.getCookies();//这里返回的是数组,说明Cookie可能存在多个
if (cookies == null) {
writer.print("这是您第一次访问本站!");
} else {
writer.print("您上一次访问本站的时间是:" );
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if ("lastLoginTime".equals(cookie.getName())) {
long lastLoginTime = Long.parseLong(cookie.getValue());
Date date = new Date(lastLoginTime);
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
writer.print(sd.format(date));
}
}
}
//添加 or 更新
Cookie cookie = new Cookie("lastLoginTime", "" + System.currentTimeMillis());
//设置cookie为1天
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);
writer.flush();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
演示二
public class CookieDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决中文乱码
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
PrintWriter writer = resp.getWriter();
//cookie,服务器从客户端中获取
Cookie[] cookies = req.getCookies();
if (cookies == null) {
writer.print("这是您第一次访问本站!");
} else {
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if ("name".equals(cookie.getName())) {
//防止网络传输中文乱码问题
writer.print(URLDecoder.decode(cookie.getValue(), "UTF-8"));
}
}
}
//添加 or 更新
Cookie cookie = new Cookie("name", URLEncoder.encode("狂神", "UTF-8"));
resp.addCookie(cookie);
writer.flush();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}