天天看點

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;

}

}