寫cookies遇到的問題

BUG問題

1.該問題是無法利用new Date對cookies設置值.能打印,轉爲字符串也行,代碼真沒問題但是就是不行.

解決方法:利用system.cruentTimeMillis獲取秒數,然後利用new Date()的構造函數解決.

但是我總感覺不是代碼出現了問題,而是…自己試試我也想知道

修改之前:

/*
 * 使用Cookie記錄客戶端上次訪問的時間
 * 
 * 思路:
 *     訪問時獲取想要的Cookie 如果沒有獲取到說明是第一次訪問,把當前時間存到一個Cookie中響應給客戶端    
 *     如果獲取到了,從cookie中取時間(上次訪問時間),再把當前時間存入Cookie中
 * 
 * */
public class CookieDemo4Servlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	   this.doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
        response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		Cookie[] cs = request.getCookies();
		
		Cookie c = CookieUtils.findCookieByName("lasttime", cs);
		
		/*if(cs!=null){
			
			for(Cookie cc:cs){
				
				if(cc.getName().equals("lasttime")){
					c = cc;
					break;
				}
			}
		}*/
		
		if(c!=null){
			out.print("<h1>上次訪問時間爲:"+c.getValue()+"</h1>");
		}else{  //第一次訪問
			out.print("<h1>歡迎第一次訪問</h1>");
		}
		
		Cookie cookie = new Cookie("lasttime",new Date()+"");
		cookie.setMaxAge(10000);
		response.addCookie(cookie);
		
		
	}

}

修改之後:


/*
 * 使用Cookie記錄客戶端上次訪問的時間
 * 
 * 思路:
 *     訪問時獲取想要的Cookie 如果沒有獲取到說明是第一次訪問,把當前時間存到一個Cookie中響應給客戶端    
 *     如果獲取到了,從cookie中取時間(上次訪問時間),再把當前時間存入Cookie中
 * 
 * */
@WebServlet("/CookieDemo4Servlet")
public class CookieDemo4Servlet extends HttpServlet {
	
	@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	   this.doPost(request, response);
	}

	
	@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
        response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		Cookie[] cs = request.getCookies();
		
		Cookie c = CookieUtils.findCookieByName("lasttime", cs);
		
		/*if(cs!=null){
			
			for(Cookie cc:cs){
				
				if(cc.getName().equals("lasttime")){
					c = cc;
					break;
				}
			}
		}*/
		
		if(c!=null){
            long cookieValue = Long.parseLong (c.getValue ( ));       //得到用戶的上次訪問時間
            Date date = new Date (cookieValue);                      //將long轉換爲日期
			out.print("<h1>上次訪問時間爲:"+date+"</h1>");
		}else{  //第一次訪問
			out.print("<h1>歡迎第一次訪問</h1>");
		}

		Cookie cookie = new Cookie("lasttime",System.currentTimeMillis () + "");
		cookie.setMaxAge(60*20*24);
		cookie.setPath ("/");
		response.addCookie(cookie);

    }

}

涉及到的cookie工具類

public class CookieUtils {
	
	public static Cookie findCookieByName(String name,Cookie[] cs){
		
		if(cs!=null){
			for(Cookie c:cs){
				if(name.equals(c.getName())){
					return c;
				}
			}
		}
		return null;
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章