java中cookie操作詳細

來源:互聯網
上載者:User

1.設定Cookie

 代碼如下 複製代碼

  Cookie cookie = new Cookie("key", "value");

  cookie.setMaxAge(60);

  設定60秒生存期,如果設定為負值的話,則為瀏覽器進程Cookie(記憶體中儲存),關閉瀏覽器就失效。

 代碼如下 複製代碼

  cookie.setPath("/test/test2");

  設定Cookie路徑,不設定的話為當前路徑(對於Servlet來說為request.getContextPath() + web.xml裡配置的該Servlet的url-pattern路徑部分) 。

 代碼如下 複製代碼

  response.addCookie(cookie);

  2.讀取Cookie

  該方法可以讀取當前路徑以及“直接父路徑”的所有Cookie對象,如果沒有任何Cookie的話,則返回null。

 

 代碼如下 複製代碼
 Cookie[] cookies = request.getCookies();

  3.刪除Cookie

 代碼如下 複製代碼

  Cookie cookie = new Cookie("key", null);

  cookie.setMaxAge(0);

  設定為0為立即刪除該Cookie;

 代碼如下 複製代碼

  cookie.setPath("/test/test2");

  刪除指定路徑上的Cookie,不設定該路徑,預設為刪除當前路徑Cookie;

  

 代碼如下 複製代碼
response.addCookie(cookie);

下面用一個完整的執行個體來說明

 

 代碼如下 複製代碼

<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>

<body>
<%
    String username = null;
    Cookie[] cookies = request.getCookies();
    if(cookies!=null)
    {
        for(int i=0;i<cookies.length;i++)
        {
            if("cookies_user".equals(cookies[i].getName()))
            {
                username = cookies[i].getValue();//cookies_user}
        }
       
        if("onepc".equals(username))
        {
            out.println("Hello");
        }else
        {
        %>
       
<table width="302" border="1">
  <form id="form1" name="form1" method="post" action="clogin.jsp">
  <tr>

    <td width="79"><div align="center"></div></td>
    <td width="207"><input type="text" name="user" id="user" /></td>
  </tr>
  <tr>
    <td><div align="center"></div></td>
    <td><input type="text" name="textfield2" id="textfield2" /></td>
  </tr>
  <tr>
    <td><div align="center">     
    </div></td>
    <td><select name="select" id="select">
      <option value="31536000">one year</option>
      <option value="120">two min</option>
      </select></td>
  </tr>
  <tr>
    <td colspan="2"><label>
      <input type="submit" name="button" id="button" value="" />
    </label></td>

  </tr>
      </form>
</table>

        <%
        }
   
    }

%>


</body>
</html>


login.jsp

 代碼如下 複製代碼

<%
    String user = request.getParameter("user");
    Cookie cookie = new Cookie("cookies_user",user);
    cookie.setMaxAge(120);
    response.addCookie(cookie);
    response.sendRedirect("cindex.jsp");

%>


 4.注意:假設路徑結構如下

  

 代碼如下 複製代碼
test/test2/test345/test555/test666

  a.相同鍵名的Cookie(值可以相同或不同)可以存在於不同的路徑下。

  b. 刪除時,如果當前路徑下沒有鍵為"key"的Cookie,則查詢全部父路徑,檢索到就執行刪除操作(每次只能刪除一個與自己最近的父路徑Cookie)   FF.必須指定與設定cookie時使用的相同路徑來刪除改cookie,而且cookie的鍵名不論大寫、小寫或大小混合都要指定路徑。IE.鍵名小寫時,如果當前路徑為/test/test2,如果找不到再向上查詢/test、/test555、/test345,如果還找不到就查詢/(/test555/test666不查詢) 。鍵名大小寫混合或大寫時,不指定路徑則預設刪除當前路徑,並且不向上查詢。

  c.讀取Cookie時只能讀取直接父路徑的Cookie。如果當前路徑為/test/test2,要讀取的鍵為“key”。當前路徑讀取後,還要讀取/test,/test讀取後,還要讀取/ 。

  d.在做Java的web項目時,由於一般的Web伺服器(如Tomcat或Jetty)都用Context來管理不同的Web Application,這樣對於每個Context有不同的Path,在一個Server中有多個Web Application時要特別小心,不要設定Path為/的Cookie,容易誤操作(當然前提是網域名稱相同) 。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.