## 效果的實現:
在服務器中的Servlet判斷是否有一個名為lastTime的cookie
1. 有:不是第一次訪問
1. 響應數據:歡迎回來,您上次訪問時間為:yyyy年MM月dd日 HH:mm:ss
2. 寫回Cookie:lastTime=yyyy年MM月dd日 HH:mm:ss
2. 沒有:是第一次訪問
1. 響應數據:您好,歡迎您首次訪問
2. 寫回Cookie:lastTime=yyyy年MM月dd日 HH:mm:ss
## 存在問題:
每一次刷新會顯示上一次訪問servlet的時間 ,只適用於同一個瀏覽器 ,更換瀏覽器再次訪問就該使用session技術了,因為cookie是瀏覽器端技術,cookie保存在瀏覽器之中,換另外一個瀏覽器,雖然是訪問的同一個servlet,但是cookie只存在原來的瀏覽器之中,所以更換了瀏覽器就不會接收原來的cookie了 。
首次打開:
網頁再次打開后再打開:
代碼:
package cn.stormtides.cookie; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URLDecoder; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.Date; @WebServlet("/cookieTest") public class CookieTest extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //設置響應的消息體的數據格式以及編碼 response.setContentType("text/html;charset=utf-8"); boolean flag=false; //1.獲取所有Cookie Cookie[] cookies = request.getCookies(); //2.遍歷cookie數組 if (cookies!=null&&cookies.length>0){ for (Cookie cookie:cookies){ //3.獲取cookie的名稱 String name=cookie.getName(); //4.判斷cookie名稱是否是:lastTime if ("lastTime".equals(name)){ //第一次訪問會存儲name="lastTime",返回結果如果是true,則不是第一次訪問 //有lastTime的cookie flag=true; //設置Cookie的value //獲取當前時間的字符串,重新設置Cookie的值,重新發送cookie Date date=new Date(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); String str_date = sdf.format(date); //URL編碼 System.out.println("編碼前:"+str_date); str_date= URLEncoder.encode(str_date,"utf-8"); System.out.println("編碼后:"+str_date); cookie.setValue(str_date); //設置cookie的存活時間 cookie.setMaxAge(60*60*24*30);//一個月 response.addCookie(cookie); //響應數據 //獲取Cookie的value,時間 String value = cookie.getValue(); //URL解碼: System.out.println("解碼前:"+value); value= URLDecoder.decode(value,"utf-8"); System.out.println("解碼后:"+value); response.getWriter().write("<h1>歡迎回來,你上次訪問的時間"+value+"</h1>"); break; } } } if (cookies == null || cookies.length == 0 || flag == false ){ //第一次訪問 Date date=new Date(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); String str_date = sdf.format(date); System.out.println("編碼前:"+str_date); str_date= URLEncoder.encode(str_date,"utf-8"); System.out.println("編碼后:"+str_date); Cookie cookie=new Cookie("lastTime",str_date); cookie.setValue(str_date); cookie.setMaxAge(60*60*24*30); response.addCookie(cookie); response.getWriter().write("<h1>歡迎回來,首次登陸</h1>"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } }
至於為什么需要URL編碼,因為在使用 SimpleDateFormat 時間格式化對象時,由於"yyyy年MM月dd日 HH:mm:ss"中的" "( 空格 )參數異常,Cookie不支持空格,所以可以刪掉空格,但是為了美觀,需要URL編碼和解碼實現數據的存儲與轉換。