當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Javax.servlet.http.Cookie用法及代碼示例

許多網站使用稱為 cookie 的小文本字符串來存儲連接之間的持久客戶端狀態。 Cookie 在請求和響應的 HTTP 標頭中從服務器傳遞到客戶端,然後再次傳遞返回。服務器可以使用 Cookie 來指示會話 ID、購物車內容、登錄憑據、用戶首選項等。

How Cookies work?

How cookies work?

從上圖可以看出,當用戶第一次請求頁麵時,服務器與資源一起發送一個 cookie 對象以存儲在客戶端的計算機上。該對象可能包含請求的詳細信息。現在,如果用戶再次請求相同的資源,它會隨請求一起發送存儲的 cookie,服務器可以使用該 cookie 來進一步增強用戶的體驗。

Cookie 的屬性:

  • 名稱=值對:這說明了 cookie 中存儲的實際信息。名稱和值均不應包含空格或以下任何字符:[ ] ( ) = , ” /? @:;
    有效 cookie name-value 對的示例:
     Set-Cookie:session-id = 187-4969589-3049309
  • Domain:默認情況下,cookie 適用於它來自的服務器。如果 cookie 最初是由 www.foo.example.com 設置的,則瀏覽器隻會將該 cookie 發送回 www.foo.example.com。但是,站點還可以指示 cookie 適用於整個子域,而不僅僅是原始服務器。例如,此請求為整個 foo.example.com 域設置用戶 cookie:
    瀏覽器不僅會將此 cookie 回顯給 www.foo.example.com,還會回顯給 lothar.foo.example.com、eliza.foo.example.com、enoch.foo.example.com 以及任何其他主機。在foo.example.com 域中。但是,服務器隻能為其直接所屬的域設置 cookie。 www.foo.example.com 無法為 www.geeksforgeeks.org、example.com 或 .com 設置 cookie,無論它如何設置域。
     Set-Cookie: user = geek ;Domain =.foo.example.com
  • Path:當從同一服務器請求子樹中的文檔時,客戶端會回顯該 cookie。但是,它不使用站點上其他目錄中的 cookie。
    Set-Cookie: user = geek; Path =/ restricted
  • Expires :該日期過後,瀏覽器應從緩存中刪除 cookie。
     Set-Cookie: user = geek; expires = Wed, 21-Feb-2017 15:23:00 IST
  • Max-Age:此屬性將 cookie 設置為在經過一定秒數後而不是在特定時刻過期。例如,此 cookie 在首次設置後一小時(3,600 秒)過期。
    Set-Cookie: user = "geek"; Max-Age = 3600

構造函數:使用指定的name-value對創建一個cookie。

Syntax : public Cookie(String name, String value)
Parameters :
name : name of the cookie
value : value associated with this cookie

方法:

  1. setDomain():設置此 cookie 可見的域。前麵在cookie部分的屬性中詳細解釋了域。
    Syntax : public void setDomain(String pattern)
    Parameters :
    pattern : string representing the domain in which this cookie is visible.
  2. getDomain():返回此 cookie 可見的域。
    Syntax : public String getDomain()
  3. setComment():指定此 cookie 的用途。
    Syntax : public void setComment(String purpose)
    Parameters :
    purpose : string representing the purpose of this cookie.
  4. getComment():返回表示此 cookie 用途的字符串。
    Syntax : public String getComment()
  5. setMaxAge():指定此 cookie 過期之前經過的時間(以秒為單位)。
    Syntax : public void setMaxAge(long time)
    Parameters :
    time : time in seconds before this cookie expires
  6. getMaxAge():返回此 cookie 的最大年齡部分。
    Syntax : public String getMaxAge()
  7. setPath():指定客戶端應將 cookie 返回到的 cookie 路徑。
    Syntax : public void setPath(String path)
    Parameters :
    path : path where this cookie is returned
  8. getPath():返回此 cookie 的路徑部分。
    Syntax : public String getMaxAge()
  9. setSecure():指示發送此 cookie 時是否使用安全協議。默認值為 false。
    Syntax : public void setSecure(boolean secure)
    參數:
    secure - If true, the cookie can only be sent over a secure
    protocol like https. 
    If false, it can be sent over any protocol.
  10. getSecure():如果此 cookie 必須是,則返回 true
    由安全協議發送,否則為 false。
    Syntax : public boolean getSecure()
  11. getName():返回 cookie 的名稱。
     Syntax : public String getName()
  12. setValue():初始化後為 cookie 分配新值。
    Syntax : public void setValue(String newValue)
    Parameters :
    newValue - a String specifying the new value
  13. getValue :返回 cookie 的值。
    Syntax : public String getValue()
  14. getVersion():如果 cookie 符合原始 Netscape 規範,則返回 0; 1 如果 cookie 符合 RFC 2965/2109
    Syntax : public int getVersion()
  15. setVersion():用於設置此 cookie 使用的 cookie 協議的版本。
    Syntax :public void setVersion(int v)
    Parameters :
    v - 0 for original Netscape specification; 1 for RFC 2965/2109
    
  16. clone():返回此 cookie 的副本。
    Syntax : public Cookie clone()

下麵是一個簡單 servlet 程序的 Java 實現,當用戶第一次請求它時,它會在瀏覽器中存儲一個 cookie,然後對於進一步的請求,它會顯示存儲的 cookie。


// Java program to illustrate methods 
// of Cookie class 
import java.io.IOException; 
import java.io.PrintWriter; 
import java.util.List; 
import javax.servlet.ServletException; 
import javax.servlet.annotation.WebServlet; 
import javax.servlet.http.Cookie; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
  
/** 
 * Servlet implementation class cookieTest 
 */
@WebServlet("/cookieTest") 
public class cookieTest extends HttpServlet  
{ 
    private static final long serialVersionUID = 1L; 
  
    /** 
     * @see HttpServlet#HttpServlet() 
     */
    public cookieTest() { 
        super(); 
        // TODO Auto-generated constructor stub 
    } 
  
    /** 
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse 
     *      response) 
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException  
    { 
  
        response.setContentType("text/html"); 
        // Create a new cookie with the name test cookie 
        // and value 123 
        Cookie cookie = new Cookie("test_cookie", "123"); 
  
        // setComment() method 
        cookie.setComment("Just for testing"); 
  
        // setDomain() method 
        // cookie.setDomain("domain"); 
  
        // setMaxAge() method 
        cookie.setMaxAge(3600); 
  
        // setPath() method 
        cookie.setPath("/articles"); 
  
        // setSecure() method 
        cookie.setSecure(false); 
  
        // setValue() method 
        cookie.setValue("321"); 
  
        // setVersion() method 
        cookie.setVersion(0); 
  
        response.addCookie(cookie); 
  
        PrintWriter pw = response.getWriter(); 
        pw.print("<html><head></head><body>"); 
        Cookie ck[] = request.getCookies(); 
  
        if (ck == null) { 
            pw.print("<p>This is first time the page is requested.</p>"); 
            pw.print("<p>And therefore no cookies found</p></body></html>"); 
        } else { 
            pw.print("<p>Welcome Again...Cookies found</p>"); 
            for (int i = 0; i < ck.length; i++) { 
  
                // getName() method 
                pw.print("<p>Name :" + ck[i].getName() + "</p>"); 
  
                // getValue() method 
                pw.print("<p>Value :" + ck[i].getValue() + "</p>"); 
  
                // getDomain() method 
                pw.print("<p>Domain :" + ck[i].getDomain() + "</p>"); 
  
                // getPath() method 
                pw.print("<p>Name :" + ck[i].getPath() + "</p>"); 
  
                // getMaxAge() method 
                pw.print("<p>Max Age :" + ck[i].getMaxAge() + "</p>"); 
  
                // getComment() method 
                pw.print("<p>Comment :" + ck[i].getComment() + "</p>"); 
  
                // getSecure() method 
                pw.print("<p>Name :" + ck[i].getSecure() + "</p>"); 
  
                // getVersion() method 
                pw.print("<p>Version :" + ck[i].getVersion() + "</p>"); 
            } 
            pw.print("<body></html>"); 
  
        } 
        pw.close(); 
    } 
  
    /** 
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse 
     *      response) 
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException  
    { 
      
        doGet(request, response); 
    } 
  
} 

輸出:以下輸出來自網絡瀏覽器 -
對於第一個請求:

This is first time the page is requested.
And therefore no cookies found.

對於第二個請求:

Welcome Again...Cookies found
Name :test_cookie
Value :321
Domain :null
Name :null
Max Age :-1
Comment :null
Name :false
Version :0

How to run the above program?

首先,確保您安裝了 Apache Tomcat 等服務器,並使用您正在使用的工具(如 Eclipse)進行了配置。隻需在服務器或本地瀏覽器上運行上述程序,隻需輸入您正在使用的服務器目錄的完整地址即可。
CookieTest servlet,一個執行三項任務的 servlet:

  1. 首先,servlet 設置一個名為 test_cookie 的 cookie。程序中的其他行設置cookie的屬性,例如最大年齡、域、值等。
  2. 其次,servlet 使用request.getCookies 查找所有傳入的 cookie 並顯示它們的名稱和其他相應屬性。
  3. 如果像第一次請求一樣沒有找到 cookie,則會顯示一條簡單的顯示消息,告訴您這是第一次訪問該頁麵。

參考:Official Java Documentation



相關用法


注:本文由純淨天空篩選整理自佚名大神的英文原創作品 Javax.servlet.http.Cookie class in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。