天天看点

Cookie显示上一次的访问时间

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

//设置中文乱码问题

response.setContentType("text/html;charset=UTF-8");

//获取所有的cookie

Cookie[] cookies = request.getCookies();

//通过指定Cookie名称来查找Cookie Cookie c = new Cookie("last","当前时间");

Cookie cookie = MyCookieUtil.getCookieByName(cookies,"last");

//判断是否为空,如果是空,说明第一次访问

if(cookie == null){

response.getWriter().write("<h3>welcome</h3>");

}else{

String value = cookie.getValue();

response.getWriter().write("<h3>welcome again "+"上次"+value+"</h3>");

}

//记录当前时间

Date date = new Date();

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");

String sDate = sdf.format(date);

//回写到浏览器

Cookie c = new Cookie("last",sDate);

response.addCookie(c);

}

package utils;

import javax.servlet.http.Cookie;

public class MyCookieUtil {

public static Cookie getCookieByName(Cookie[] cookies,String name){

if(cookies == null){

return null;

}else{

//循环遍历,和name匹配,成功返回当前的COOKIE

for(Cookie cookie : cookies){

if(cookie.getName().equals(name)){

return cookie;

}

}

}

return null;

}

}