Cookie的用法

                                   <><>讓我告訴你Cookie的用法<><>
  《《《《《《《《《《《下面是我親手實現的使用cookie例子,希望幫助有需要的人學習(完整源碼)》》》》》》》》》

》》》author:何桂坤

   ==兩個頁面一個jsp,一個servlet,不要看到那麼代碼就煩,老大很簡單的,把他們複製就可以直接用了.
 《《《《《《《《《《《======1.jsp頁面======》》》》》》》》》》》》

   <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
   <%
   String path = request.getContextPath();
   String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
   %>

  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  <html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'userCookie.jsp' starting page</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
  </head>
 
   <body>
     <form name="form1" method="post" action="ServletCookie">   
       <input type="submit" name="Submit" value="訪問cookie">  
     </form>
   </body>
  </html>

   《《《《《《《《《《《======2.Servlet======》》》》》》》》》》》》

 package cookie;//包名

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 ServletCookie extends HttpServlet {
 public ServletCookie() {
  super();
 }

 public void destroy() {
  super.destroy(); // Just puts "destroy" string in log
 }

 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  doPost(request, response);
 }

 /**
  * The doPost method of the servlet. <br>
  * This method is called when a form has its tag value method equals to
  * post.
  *
  * @param request
  *            the request send by the client to the server
  * @param response
  *            the response send by the server to the client
  * @throws ServletException
  *             if an error occurred
  * @throws IOException
  *             if an error occurred
  */
 /*《====Cookie的用法與session的用法極類似 只是session是在服務器用的 而cookie是在客戶端用的====》
  * @author-何桂坤-2010-9-28
         * 方法詳解
  * String getComment() 返回cookie中註釋,如果沒有註釋的話將返回空值.
  * String getDomain() 返回cookie中Cookie適用的域名
  * int getMaxAge() 返回Cookie過期之前的最大時間,以秒計算。
  * String getName() 返回Cookie的名字。名字和值是我們始終關心的兩個部分
  * String getValue() 返回Cookie的值
  * String getPath() 返回Cookie適用的路徑
  * boolean getSecure() 如果瀏覽器通過安全協議發送cookies將返回true值,如果瀏覽器使用標準協議則返回false值。
  * int getVersion() 返回Cookie所遵從的協議版本。
  * void setComment(String purpose) 設置cookie中註釋。
  *void setDomain(String pattern) 設置cookie中Cookie適用的域名
  *void setMaxAge(int expiry) 以秒計算,設置Cookie過期時間。
  *void setPath(String uri) 指定Cookie適用的路徑。
  *void setSecure(boolean flag) 指出瀏覽器使用的安全協議,例如HTTPS或SSL。
  *void setValue(String newValue) cookie創建後設置一個新的值。
  *void setVersion(int v) 設置Cookie所遵從的協議版本
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  response.setContentType("text/html;charset=gb2312");// 設置編碼
  PrintWriter out = response.getWriter();
  Cookie[] cookies = request.getCookies();// 獲得cookies數組
  int count = 0;
  boolean bool = true;// 第一次標識假值
  Cookie cookie = null;// 聲明單個cookie
  if (cookies != null) {
   // 循環數組
   for (int i = 0; i < cookies.length; i++) {
    cookie = cookies[i];// 獲得數組裏面的值
    // 判斷cookie的名稱是否爲heguikun
    if ("heguikun".equals(cookie.getName())) {
     // 取出次數並累加一
     count = Integer.parseInt(cookie.getValue()) + 1;
     cookie.setValue(count + "");// 重新設置cookie累加後的值
     cookie.setMaxAge(60 * 60 * 24);// 有效時間 60s*60s*24 = 一天
     response.addCookie(cookie);// 返回到客戶端
     out.println("你是第" + count + "次登錄該網頁。");// 頁面顯示登錄該網頁的次數
     bool = false;// 不是第一次後標識真值
    }
    if ("useName".equals(cookie.getName())) {
     out.println("<br/>");
     out.println("本次登錄的用戶爲:" + cookie.getValue());// 頁面顯示登錄該網頁的次數
     out.println("<br/>");
     out.println("<br/>");
     response.addCookie(cookie);// 返回到客戶端
    }
   }
  }
  if (bool) {// 第一次訪問是進入
   out.println("你是第 1 次登錄該網頁。在此之前沒有相關Cookie信息。");
   cookie = new Cookie("heguikun", "1");// 把訪問次數放到cookie中
   // 默認該cookie是存儲在瀏覽器的內在中,用戶關閉瀏覽器則被刪除,下面的方法是將cookie存儲在硬盤上。
   //默認存到C盤下  在Intent選項中可以打開這個文件夾
   cookie.setMaxAge(60 * 60 * 24);// 設置最大時效一天,如果設置爲0則是刪除該cookie
   response.addCookie(cookie);// 返回到客戶端

   Cookie cookieUser = new Cookie("useName", "heguikun");// 把登錄用戶放到cookie中,不能存儲中文,
   cookieUser.setMaxAge(60 * 60 * 24);
   response.addCookie(cookieUser);// 返回到客戶端
  }
  out.println("<a href='cookie/userCookie.jsp'>返回首頁 </a>");
  out.flush();
  out.close();
 }

 public void init() throws ServletException {
  // Put your code here
 }
 //代碼來自heguikun個人項目
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章