Cookie在PHP和JSP中应用两例
系统环境:win2000、apache、php4、tomcat、jdk1.2.2 

1.cookie.php 
<? 
  
//PHP中变量可以直接用 
  
echo $cookie_user
  if(
$submit){ 
    
//int setcookie(string name, string value, int expire, string path, string domain, int secure); 
    //setcookie函数可设定变量名、值、生存时间、路径、网站、安全传输 
    
setcookie("cookie_user",$user,time()+9999999); 
    echo 
"<a href=cookie.php>查看cookie</a>"
  }else{ 
?> 

<html> 
<head><title>Cookie</title></head> 
<body> 
<form action="<?echo $PHP_SELF;?>" method="post"> 
<pre> 
名称:<input type="text" name="user"><br> 
<input type="submit" name="submit" value="确定"> 
</pre> 
</form> 

<? 
  

?> 
此程序在本机调试通过 

2.cookie.jsp 
<%@ page language="java" %> 
<%@ page import="java.lang.*" %> 
<%@ page contentType="text/html; charset=gb2312" %> 
<%@ page import="java.util.*" %> 
<% 
   String answerNum=null ; 
   //定义和取得cookie 
   Cookie[] cookies=request.getCookies(); 
   
   if( cookies!=null ) 
     for( int i=0 ; i<cookies.length ; i++ ) 
       //取得cookie中的变量值 
       if( cookies[i].getName().equals( "ANSWER" ) ) 
            answerNum=cookies[i].getValue() ; 

   String guessNum=null ; 
   String message=null ; 
   boolean gameOver=false ; 

   if( answerNum==null ) { 
     answerNum="4"; 
     //定义新的cookie 
     Cookie c=new Cookie( "ANSWER", answerNum ) ; 
     response.addCookie( c ) ; 
   } 
   else {   
     guessNum=request.getParameter("guess_number"); 
     
     if(guessNum.compareTo(answerNum)==0) { 
       gameOver=true ; 
       message="真厉害"; 
       //重置cookie 
       Cookie c=new Cookie( "ANSWER", "" ) ; 
       c.setMaxAge( 0 ) ; 
       response.addCookie( c ) ; 
     }else{ 
        
       message="再来一次"; 
     } 
   } 
%> 
<html> 
<title> 
猜数字游戏 
</title> 
<body bgcolor="#FFFFFF"> 
<h1>猜数字游戏!</h1> 

<% 
    if( message!=null ) { 
%> 
      <%=message %> 
<% 
    } 

    if( gameOver ) { 
%> 
<form name="form2" method="get" action="cookie.jsp" > 
  <input type="submit" name="submit" value="继续" > 
</form> 
<% 
    }else{ 
%> 
   <form name="form1" method="get" action="cookie.jsp" > 
  请输入1位数: 
  <input type="text" name="guess_number" size="4" maxlength="1" > 
  <input type="submit" name="submit" value="输入" > 
</form> 
<% 
    } 
%> 
</body> 
</html> 

此程序在本机调试通过