读取Cookie

Code:
  1. //如何读取Cookie案例  
  2. package com.tsinghua;  
  3.   
  4. import javax.servlet.http.*;  
  5. import java.io.*;  
  6.   
  7. public class CookieTest2 extends HttpServlet{  
  8.   
  9.     //处理get请求  
  10.     public void doGet(HttpServletRequest req,HttpServletResponse res){  
  11.         try{  
  12.             res.setContentType("text/html;charset=gbk");  
  13.             PrintWriter pw=res.getWriter();  
  14.               
  15.             //从客户端得到所有的cookie信息  
  16.             Cookie []allCookies=req.getCookies();  
  17.               
  18.             int i=0;  
  19.             if(allCookies!=null){  
  20.                 //从中读取Cookie  
  21.                 for(i=0;i<allCookies.length;i++){  
  22.                     //依次取出  
  23.                     Cookie temp=allCookies[i];  
  24.                     if(temp.getName().equals("color1")){  
  25.                         //得到Cookie的值  
  26.                         String val=temp.getValue();  
  27.                           
  28.                         pw.println("color1="+val);  
  29.                         break;  
  30.                     }  
  31.                 }  
  32.                 if(allCookies.length==i){  
  33.                     pw.println("Cookie过期!");  
  34.                 }  
  35.                   
  36.             }else{  
  37.                 pw.println("不存在color1这个Cookie或是过期!");  
  38.             }  
  39.         }catch(Exception e){  
  40.             e.printStackTrace();  
  41.         }  
  42.     }    
  43. }  

 

 

posted @ 2010-08-03 08:11  成长的企鹅  阅读(162)  评论(0编辑  收藏  举报