cooklie的特点和作用
1. cookie存储数据在客户端浏览器
2.浏览器对于单个cookie 的大小有限制(4kb)以及对同一个域名下的总cookie数量也有限制(2o个)
作用:
1. cookie—般用于存出少量的不太敏感的数据
2.在不登录的情况下,完成服务器对客户端的身份识别
会话技术_案例_分析和代码:
可以采用Cookie来完成
在服务器中的Servlet判断是否有一个名为lastTime的cookie
有:不是第一次访问。
响应数据:欢迎回来,您上次访问为2022年8月11日15:29:37
写回Cookie:lastTime2022年8月11日15:30:15
没有:是第一次访问
响应数据:您好,欢迎您首次访问。
写回Cookie:lastTime=2022年8月11日15:32:54
@WebServlet("/CookieDemo6")
public class CookieDemo6 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
Cookie[] cookies = request.getCookies();
boolean flag = false;
if (cookies !=null && cookies.length>0){
for (Cookie cookie : cookies) {
String name = cookie.getName();
if ("lastTime".equals(name)){
flag = true;
String value = cookie.getValue();
System.out.println("解码前:"+value);
value = URLDecoder.decode(value, "utf-8");
System.out.println("解码后:"+value);
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String format = sdf.format(date);
System.out.println("编码前:"+format);
format = URLEncoder.encode(format, "utf-8");
System.out.println("编码后:"+format);
cookie.setValue(format);
cookie.setMaxAge(60*60*24*30);
response.addCookie(cookie);
response.getWriter().write("<h1>欢迎回来,您上次访问时间为:"+value+"</h1>");
break;
}
}
}
if (cookies == null || cookies.length == 0 || flag == false){
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String format = simpleDateFormat.format(date);
System.out.println("编码前"+format);
format = URLEncoder.encode(format,"utf-8");
System.out.println("编码后"+format);
Cookie cookie = new Cookie("lastTime",format);
cookie.setValue(format);
cookie.setMaxAge(60*60*24*30);
response.addCookie(cookie);
response.getWriter().write("<h1>您好,欢迎您首页访问成功</h1>");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
浙公网安备 33010602011771号