Cookie用法简介 一、Cookie简介1、Cookie概念: Cookie的格式实际上是一段纯文本信息, 由服务器随着网页一起发送到客户端, 并保存在客户端硬盘中指定的目录的.2、Cookie中的常用的方法getComment()/setComment():获取/设置Cookie的注释getDomain()/setDomain():获取/设置Cookie适用的域getMaxAge()/setMaxAge():获取/设置Cookie过期之前的时间,以秒计。如不设,只在当前会 话内有效getName()/setName():获取/设置Cookie的名字getPath()/setPath():获取/设置Cookie适用的路径getSecure()/setSecure():获取/设置一个boolean值,该值表示Cookie是否只能通过加密的连 接发送getValue()/setValue():获取/设置Cookie的值getVersion()/setValue():获取/设置Cookie所遵从的协议版本3、Cookie的创建和如何用JSP把它写入硬盘Cookie usernameCookie=new Cookie("username","value"); response.addCookie(userCookie);4、如何用JSP读取Cookie中的内容. 从客户端读取Cookie时调用的是request对象的getCookies()方法,得到一个Cookie对象的数组,这时可以编写一个得到指定名称的Cookie对象值的方法:public static String getCookieValue(Cookie[] cookies,String cookieName,String defaultValu){ for(int i=0;i<cookies.length;i++){ Cookie cookie=cookies; if(cookieName.equals(cookie.getName())) return(cookie.getValue()); } return(defaultValue);}二、本人用Cookie的简单JSP应用。1、程序简介: 本程序是一个网站计数器,当用户登陆到本网页的时候网站的计数器会自动加1,也就是增加了一个用户的访问,当用户以同样身份登陆的时候计数器不动自动加1,只会显示网站访问的次数。本例子有二个页面,一个是用户登陆页面:用来输入用户名、密码等信息。第二个就是计数器页面:用JSP中的application对象中的一个方法做计数器,当用户登陆时检查客户端的Cookie如果Cookie中有此用户,就把网站的访问人数显示出来,如果客户端的Cookie中没有此用户,就把计数器加1,再显示出来,最后把用户名写入Cookie中。下次用户再以此用名访问的时候就只会显示访问人数而不会自动增加1。 登陆页面程序tijiao.htm代码如下:<html><head><title></title><meta http-equiv="Content-Type" content="text/html; charset=gb2312"></head> <body bgcolor="#FFFFFF" text="#000000"><p> </p><p> </p><p> </p><p> </p><table width="100%" border="0" height="741"> <tr> <td> <form name="form1" method="post" action="jishu.jsp"> <p align="center"> 用户名:<input type="text" name="textfield"> </p> <p align="center">密 码: <input type="password" name="textfield2"> </p> <p align="center"> <input type="submit" name="submit" value="提交"> </p> </form> </td> </tr> <tr> <td> </td> </tr> <tr> <td> </td> </tr> <tr> <td> </td> </tr> <tr> <td> </td> </tr></table></body></html>计数器jishu.jsp程序代码如下:<%@ page language="java" contentType="text/html; charset=gb2312"%><% if(application.getAttribute("counter")==null) {application.setAttribute("counter",0);}//初始化计数器 String nn=request.getParameter("textfield"); //提取登陆名 Cookie[] cookies=request.getCookies();//取客户端所有cookie for (int i=0;i<cookies.length;i++) { //输出每一个cookie的名字和内容 Cookie c=cookies; if(c.getName().toString().equals("UserName"))//判断用名是否登陆过 { if(c.getValue().toString().equals(nn)) { int count=Integer.parseInt((application.getAttribute("counter").toString())); //登陆过的只显示计数器的数字 out.println("自从应用服务器启动后,此页面已经访问了"+count+"次"); } else { int count=Integer.parseInt((application.getAttribute("counter").toString())); count++; out.println("自从应用服务器启动后,此页面已经访问了"+count+"次"); application.setAttribute("counter",new Integer(count));//没有登陆过的计数器加1显示出来,并把用户名写入cookie里。 Cookie cookie=new Cookie("UserName",nn); cookie.setComment("说明"); cookie.setMaxAge(365*24*60*60);//有效期 response.addCookie(cookie); } } }%>