日期:2014-05-19 浏览次数:20904 次
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>"); } }