Servlet Cookie更新的問題

ankyhe發表於2007-10-30
新學Java EE的Servlet程式設計,Cookie這個地方有些問題。程式碼幾乎是抄一個教材的,用Firefox檢視Cookie,發現Cookie可以成功被加入,可是卻不能更新。問問大家,不知道誰遇到這種問題沒有?程式碼如下:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Cookie ck = null;
Cookie[] cks = request.getCookies();
if(cks != null){
for(int i = 0 ; i < cks.length ; ++i){
if (cks.getName().equals(COOKIENAME)){
int times = Integer.parseInt(cks.getValue());
++times;
cks.setValue(Integer.toString(times));
ck = cks;

}
}
}
if (ck == null){ //first time
ck = new Cookie(COOKIENAME,"1");
ck.setPath(request.getContextPath());
ck.setMaxAge(10000);
response.addCookie(ck);
}

PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
out.println("<html>\n<head>\n<title>Get times</title></head><body>");
out.println("You are " + ck.getValue()+"times");
if(cks == null){
out.println("<p></p>null");
}
out.println("</body>\n</html>");



}
做的事情很簡單,記錄你訪問這個頁面的次數。可是無論怎麼重新整理,Firefox顯示Cookie就是1。線上等解答,謝謝大家。

相關文章