在服务器中的Servlet判断是否有一个名为lasttime的cookie
* 1、有,不是第一次访问
* *响应数据,欢迎回来,您上次的访问时间为。。。
* *写回cookie,lasttime=。。。
* 2、没有,是第一次访问
* *响应数据,欢迎首次访问
* *写回cookie,lasttime=。。。
@WebServlet("/CookieTest")
public class CookieTest extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1、设置响应的消息体的数据格式和编码
resp.setContentType("text/html;charset=utf-8");
// 获取所有的cookie
Cookie []cookies=req.getCookies();
boolean flge=false;//没有cookie为lasttime;
//2、遍历cookie数组
if (cookies!=null&&cookies.length>0){
for (Cookie cookie : cookies) {
//获取cookies的名称
String name= cookie.getName();
//判断名称是否是lasttime
if (name.equals("lastname")){
flge=true;
//有,不是第一次访问
//获取当前的时间字符串,重新设置cookie的值,重新发送cookie
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 hh时ss分mm秒");
String str_date=sdf.format(date);
System.out.println("编码前"+str_date);
//URL编码
str_date=URLEncoder.encode( str_date,"utf-8");
System.out.println("编码后"+str_date);
cookie.setValue("str_date");
//设置cookie的存活时间
cookie.setMaxAge(60*60*24);//一天
resp.addCookie(cookie);
//响应数据
//获取cookie的value,时间
String value=cookie.getValue();
System.out.println("解码前"+value);
//url解码
value= URLDecoder.decode(str_date,"utf-8");
System.out.println("解码后"+value);
resp.getWriter().write("欢迎再次回来,你上次登录的时间是"+value);
break;
}
}
}
if (cookies == null || cookies.length==0||flge==false){
//没有,第一次访问
//获取当前的时间字符串,重新设置cookie的值,重新发送cookie
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 hh时ss分mm秒");
String str_date=sdf.format(date);
System.out.println("编码前"+str_date);
//URL编码
str_date=URLEncoder.encode( str_date,"utf-8");
System.out.println("编码后"+str_date);
Cookie cookie1=new Cookie("lasttime","str_date");
cookie1.setValue("str_date");
//设置cookie的存活时间
cookie1.setMaxAge(60*60*24);//一天
resp.addCookie(cookie1);
resp.getWriter().write("欢迎首次访问");
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
}