日期:2014-05-19  浏览次数:20915 次

为何cookie不刷新?
Java code
import java.io.IOException; 
import javax.servlet.ServletException; 
import javax.servlet.http.Cookie; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
public class Track extends HttpServlet { 
 protected void doGet(HttpServletRequest request, 
     HttpServletResponse response) throws ServletException, IOException { 
      Cookie cookie = null; 
      Cookie[] cookies = request.getCookies( ); 
      if (cookies != null){
          for (int i = 0; i < cookies.length; i++){ 
              if (cookies[i].getName( ).equals("LK")){ 
               String v=cookies[i].getValue(); 
               int value=Integer.parseInt(v)+1; 
                 cookies[i].setValue(Integer.toString(value)); 
                 cookie=cookies[i]; 
              }  
          }//end for 
      }//end if 
       //不存在,创建cookie 
      if (cookie == null){ 
                 int maxAge=10; 
          //Create the Cookie object 
         cookie = new Cookie("LK","1"); 
          cookie.setPath(request.getContextPath( )); 
          cookie.setMaxAge(maxAge); 
          response.addCookie(cookie); 
         }//end if 
      // 显示信息 
      response.setContentType("textml;charset=gb2312"); 
      java.io.PrintWriter out = response.getWriter( ); 
      
      out.println("<html>"); 
      out.println("<head>"); 
      out.println("<title>Cookie跟踪会话 </title>");   
      out.println("</head>"); 
      out.println("<body>"); 
      out.println( 
      "<h2> 您好!</h2>"); 
       out.println("欢迎您第 "+cookie.getValue( )+"次访问本页面<br>"); 
      out.println("</body>"); 
        out.println("</html>"); 
}  
}

(java servlet)无论我怎样重启tomcat以及刷新操作,
为何总是输出:您好!
欢迎您第 2次访问本页面.

------解决方案--------------------
大哥。
 cookie.setPath(request.getContextPath( )); 
cookie.setMaxAge(maxAge); 
response.addCookie(cookie); 
这个移到if的后面。。。
原因你改了Cookie的值,只是在服务端该的。还没有重新写入客户端端
------解决方案--------------------
//不存在,创建cookie 
int maxAge=10; 
if (cookie == null){ 
//Create the Cookie object 
cookie = new Cookie("LK","1"); 
}//end if 
// 显示信息 
cookie.setPath(request.getContextPath( )); 
cookie.setMaxAge(maxAge); 
response.addCookie(cookie);