Cookie案例
Cookie案例分析
案例:记住上一次访问时间
需求:
1、访问一个Servlet,如果是第一次访问,则提示:您好,欢迎您首次访问。
2、如果不是第一次访问,则提示:欢迎回来,您上次访问时间为:显示时间字符串
分析:
1、可以采用Cookie来完成
2、在服务器中的Servlet判断是否是由一个名为lastTime的cookie
1、有:不是第一次访问
1、响应数据:欢迎回来,您上次访问时间为:显示时间字符串
2、写回Cookie:lastTime=时间
2、没有:是第一次访问
1、响应数据:您好,欢迎您首次访问
2、写回Cookie:lastTime=时间
@WebServlet("/CookieTest")
public class CookieTest extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置响应的消息体的数据格式以及编码
response.setContentType("text/html;charset=utf-8");
//1、获取所有的Cookie
Cookie[] cookies = request.getCookies();
boolean flag = false;
//2、遍历Cookie数组
if (cookies !=null && cookies.length>0){
for (Cookie cookie : cookies) {
//3、获取cookie名称
String name = cookie.getName();
//4、判断名称是否是lastTime
if ("lastTime".equals(name)){
//有该cookie,不是第一次访问
flag = true;
//响应数据
//获取cookie的value时间
String value = cookie.getValue();
//URL解码
System.out.println("解码前:"+value);
value = URLDecoder.decode(value, "utf-8");
System.out.println("解码后:"+value);
response.getWriter().write("<h1>欢迎回来,您上次访问时间为:"+value+"</h1>");
//设置cookie的value
//获取当前时间的字符串,重新设置Cookie的值,重新发送cookie
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String format = sdf.format(date);
System.out.println("编码前:"+format);
//URL编码
format = URLEncoder.encode(format, "utf-8");
System.out.println("编码后:"+format);
cookie.setValue(format);
//设置cookie的存活时间
cookie.setMaxAge(60*60*24*30);
response.addCookie(cookie);
break;
}
}
}
if (cookies==null && cookies.length==0 && flag == false){
//没有,第一次访问
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String format = sdf.format(date);
//URL编码
format = URLEncoder.encode(format, "utf-8");
Cookie cookie = new Cookie("lastTime",format);
//设置cookie的存活时间
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号