⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cookiecounter.java

📁 java网络高级编程的配套源码,java网络高级编程为清华出版社出版.
💻 JAVA
字号:
/*程序清单5-8*/

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import sun.servlet.http.Cookie;

public class CookieCounter extends HttpServlet
{
  //countername是Servlet保存的主Cookie的名字
  private static final String countername = "MyCounter";

  /*defaultInitialValue是servlet缺省初试值,是客户与服务器初试的会面值。
  在实例中可以被Servlet的初始化参数覆盖*/
  static final int defaultInitialValue=10;

  //initialValue是实例实际上的初试值
  private int initialValue;

  //初始化Servlet
  public void init(ServletConfig conf) throws ServletException
  {
    String s;
	super.init(conf);
    if((s = getInitParameter("initial")) == null)
	{
      initialValue= defaultInitialValue;
	}else
	{
      try
	  {
        initialValue= Integer.parseInt(s);
	  }
	  catch (NumberFormatException e)
	  {
        initialValue = defaultInitialValue;
		log("Non-numeric format for 'initial' parameter:" + s);
	  }
	}
  }

  //处理客户请求
  protected void doGet(HttpServletRequest req, HttpServletResponse res)
		throws ServletException.IOException
  {
     int counter = initialValue;
	 Cookie Cookies[],c = null;
	 boolean hadCookies = false, hadCounter = false;
	 //方法getCookies返回这次请求的所有Cookie
	 if ((Cookiese = Cookie.getCookies(req))!=null)
	 {
	   hadCookies = true;
	   for (int i=0;i<Cookies.length ;i++ )
	   {
	     if (Cookies[i].getName().equals(counterName))
	     {
		 try
		 {
		   //方法clone返回该Cookie对象的一个拷贝
		   c = (Cookie)Cookies[i].clone();
		   counter = Integer.parseInt(c.getValue());
		   c.setValue(Integer.toString(counter + 1));
		   hadCounter = true;
		 }
		 catch (NumberFormatException e)
		 {
		   c = null;
		 }
		 break;
	     }
	   }
	 }
	 /*不管以前有无名字为"MyCounter"的Cookie,现在都要保存它*/
     if (c == null)
     {
	   //Cookie的构造函数
	   c = new Cookie(counterName,Integer.toString(counter));
	   //给Cookie加注解
	   c.setComment("Supports Cookie Counter Demo Servlet");
	   //设定最长保存期限
	   c.setMaxAge(2*24*60*60);
	   //设定路径
	   c.setPath("/");
	   //保存Cookie
	   c.saveCookie(res);
     }
	 if (false)
	 {
	   //增加一个新的Cookie,在退出浏览器时删除!
	   c = new Cookie("gensym-"+(System.currentTimeMillis() & 0x0ff),
			new Date.toString());
	   c.setComment("Show multi-Cookies support");
	   c.saveCookie(res);
	 }
	 //产生应答信息,一个显示所有的Cookies、他们的值和属性、以及一些其它信息的HTML
	 //页面,建立一个长度为4068字节的输出缓冲区。
	 //建立一个缓冲区
	 ByteArrayOutputStream bytes;
	 //建立一个输出流
	 PrintStream out;
	 //Cookies的长度限制是4K
	 bytes = new ByteArrayOutputStream(4096);
	 //连接输出流与缓冲区
	 out = new PrintStream(bytes);
	 out.println("<html><head><title>");
	 out.println("<Cookie Counter</title></head>");
	 out.println("<body>");
	 out.println("<center><h1>Cookie Counter</h1></center>");
	 if (hadCounter)
	 {
        out.println("<center>");
		out.println("<p><em><b>Your session's counter name was");
		out.println(counter);
		out.println("before you visited this page!</b></em></p>");
		out.println("<p>The counter has been incremented.");
		out.println("</center>");
	 }
	 else 
	 {
	    out.println("<p>You presented no session Cookie.");
		out.println("A new Cookie was created with an initial counter");
		out.println("holding the value" + counter + ".");
	 }

	 if (hadCookies)
	 {
		out.println("<p>You presented these Cookies:<ol>");
		for (int i=0;i<Cookies.length ;i++ )
		{
			String temp;
			out.println("<li>Name = ");
			out.println(Cookies[i].getName());
			out.println(", Value = ");
			out.println(Cookies[i].getValue());
			//方法getDomain返回该Cookie的区域
			if ((temp = Cookies[i].getName()) != null)
			{
				out.println(", Domain = ");
				out.println(Cookies[i].getDomain());
			}
			if ((temp = Cookies[i].getPath()) != null)
			{
				out.println(", Path= ");
				out.println(Cookies[i].getPath());
			}
		}
		out.println("</ol>");
	 }
	 out.println("<p> Watch teh value of the counter change");
	 out.println(" as reload this page! The counter is updated");
	 out.println("by the servlet which dynamically generates");
	 out.println(" this web page!");

	 //方法getHeader返回请求的头部信息
	 String temp = req.getHeader("User-Agent");
	 out.println("<p> Your browser is <b>"
		+ ((temp != null)?temp:"not known!") + "</b>.");
	 out.println("<p>The cookie server's time is now <b>"
		+ new Date() + "</b>.");
	 out.println("</body></html>");
	 out.flush();
	 res.setContentType("text/html");
	 res.setContentLength(bytes.size());
	 bytes.writeTo(res.getOutputStream());
  }

  public String getServletInfo()
  {
	 return "Demonstrates the Cookie API for user sessions!";
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -