protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取cookies
response.setContentType("text/html;charset=utf-8");
Cookie[] cookies = request.getCookies();
boolean flag = false;
//返回数组遍历数组 寻找 lastTime参数
if (cookies != null && cookies.length >0){
//遍历
for (Cookie cookie : cookies) {
//获取 cookie 键 寻找 lastTime
String name = cookie.getName();
if ("lastTime".equals(name)){
flag = true;
//如果有 就不是第一次登录
Date date = new Date();
//设置时间戳格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
//返回日期
String src_date = sdf.format(date);
//设置 cookie
cookie.setValue(src_date);
//设置cookie 存活时间
cookie.setMaxAge( 60 * 60 * 24 * 30 );
//添加cookie
response.addCookie(cookie);
//获取 cookie
String value = cookie.getValue();
//打印信息
response.getWriter().write("<h1>欢迎回来,您上次的访问时间为"+ value + "</h1>");
}
}
}
if (cookies == null || cookies.length == 0 || flag == false) {
Date date = new Date();
//设置时间戳格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
//返回日期
String src_date = sdf.format(date);
//设置 cookie
Cookie cookie = new Cookie("lastTime",src_date);
//设置cookie 存活时间
cookie.setMaxAge( 60 * 60 * 24 * 30 );
//获取 cookie
response.addCookie(cookie);
response.getWriter().write("欢迎用户,您是第一次访问登录!");
}
}
评论 (0)