Servlet Cookie更新的问题

07-10-30 ankyhe
新学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。在线等解答,谢谢大家。

paradise7th
2007-11-05 11:49
你的ck为空时才执行addCookie的操作,但是更新ck时没有执行addCookie

猜你喜欢