需求:
判斷用戶是第幾次訪問本網(wǎng)站荧缘,如果是第一次那么顯示當(dāng)前時(shí)間恬汁,如果不是那么顯示上次訪問的時(shí)間
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
boolean firstVisit = true;
resp.setContentType("text/html;charset=utf-8");
//日期格式
SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日hh小時(shí)mm分鐘ss秒");
//判斷是否首次訪問
Cookie cookies[] = req.getCookies();
if (cookies!=null){
for (Cookie cookie : cookies){
if ("lastTime".equals(cookie.getName())){ //說明不是第一次訪問
//解碼得到上次訪問的時(shí)間
String lastTime = URLDecoder.decode(cookie.getValue(),"utf-8");
resp.getWriter().write("歡迎您再次訪問杠茬,上次訪問時(shí)間為:"+lastTime);
//創(chuàng)建當(dāng)前時(shí)間的Cookie且替換原來(lái)的Cookie
String date = df.format(new Date());
date = URLEncoder.encode(date,"utf-8");//中文要記得編碼
Cookie c = new Cookie("lastTime",date);
resp.addCookie(c);
//修改標(biāo)簽值
firstVisit = false;
}
}
}
if (firstVisit){ //表明是第一次
//顯示當(dāng)前時(shí)間
String date = df.format(new Date());
resp.getWriter().write("歡迎本次訪問杠袱,您當(dāng)前時(shí)間為"+date);
//添加Cookie
date = URLEncoder.encode(date,"utf-8");//中文要記得編碼
Cookie c = new Cookie("lastTime",date);
resp.addCookie(c);
}
}
cookie.gif