日期:2014-05-19 浏览次数:20670 次
import java.io.IOException; import java.io.PrintWriter; 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 cookie extends HttpServlet { public 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("VisitTimes")){ String v = cookies[i].getValue(); System.out.println(cookies[i].getValue()); int value = Integer.parseInt(v)+1; cookies[i].setValue(Integer.toString(value)); cookie=cookies[i]; System.out.println(cookies[i].getValue()); } } } if(cookie==null){ System.out.print("new "); int maxAge = 10000; cookie = new Cookie("VisitTimes","1"); cookie.setPath(request.getContextPath()); cookie.setMaxAge(maxAge); response.addCookie(cookie); } response.setContentType("text/html;charset=gb2312"); PrintWriter out = response.getWriter(); out .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>跟踪会话</TITLE></HEAD>"); out.println(" <BODY>"); out.println("<h2>您好!</h2>"); out.println("欢迎您第"+cookie.getValue()+"次访问<br>"); out.println(" </BODY>"); out.println("</HTML>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
import java.io.IOException; import java.io.PrintWriter; 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 cookie2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int count=1; Cookie cookie =null; Cookie[] cookies = request.getCookies(); if(cookies==null||cookies.length==0){ //System.out.print("new "); cookie = new Cookie("Visit","1"); //cookie.setPath(request.getContextPath()); cookie.setMaxAge(300); response.addCookie(cookie); } else{ for(int i =0;i<cookies.length;i++){ if(cookies[i].getName().