Java Servlet編程應用之Cookie使用方法

來源:互聯網
上載者:User

  Cookie 是一小塊可以嵌入HTTP 要求和響應中的資料,它在伺服器上產生,並作為回應標頭域的一部分返回使用者。瀏覽器收到包含Cookie 的響應後,會把Cookie 的內容用“關鍵字/值” 對的形式寫入到一個用戶端專為存放Cookie 的文字檔中。瀏覽器會把Cookie 及隨後產生的請求發給相同的伺服器,伺服器可以再次讀取Cookie 中存Cookie 可以進行有效期間設定,到期的Cookie 不會發送給伺服器。

  Servlet API 提供了一個Cookie 類,封裝了對Cookie 的一些操作。Servlet 可以建立一個新的Cookie,設定它的關鍵字、值及有效期間等屬性,然後把Cookie 設定在HttpServletResponse 對象中發回瀏覽器,還可以從HttpServletRequest 對象中擷取Cookie。

  編程思路:Cookie 在實際的Servlet 編程中是很廣泛應用,下面是一個從Servlet 中擷取Cookie 資訊的例子。

  ShowCookies.java 的原始碼如下:

import javax.servlet.*;
import javax.servlet.http.*;
/**
* <p>This is a simple servlet that displays all of the
* Cookies present in the request
*/
public class ShowCookies extends HttpServlet
{
 public void doGet(HttpServletRequest req, HttpServletResponse resp)
 throws ServletException, java.io.IOException
 {
  // Set the content type of the response
  resp.setContentType("text/html;charset=gb2312");
  // Get the PrintWriter to write the response
  java.io.PrintWriter out = resp.getWriter();
  // Get an array containing all of the cookies
  Cookie cookies[] = req.getCookies();
  // Write the page header
  out.println("<html>");
  out.println("<head>");
  out.println("<title>Servlet Cookie Information</title>");
  out.println("</head>");
  out.println("<body>");
  if ((cookies == null) || (cookies.length == 0)) {
   out.println("沒有 cookies ");
  }
  else {
   out.println("<center><h1>響應訊息中的Cookies 資訊 </h1>");
   // Display a table with all of the info
   out.println("<table border>");
   out.println("<tr><th>Name</th><th>Value</th>" +
"<th>Comment</th><th>Max Age</th></tr>");
   for (int i = 0; i < cookies.length; i++) {
    Cookie c = cookies[i];
    out.println("<tr><td>"+c.getName()+"</td><td>"+
    c.getValue()+"</td><td>"+c.getComment()+"</td><td>"+
c.getMaxAge()+"</td></tr>");
  }
  out.println("</table></center>");
 }
 // Wrap up
 out.println("</body>");
 out.println("</html>");
 out.flush();
}
/**
* <p>Initialize the servlet. This is called once when the
* servlet is loaded. It is guaranteed to complete before any
* requests are made to the servlet
* @param cfg Servlet configuration information
*/
public void init(ServletConfig cfg)
throws ServletException
{
 super.init(cfg);
}
/**
* <p>Destroy the servlet. This is called once when the servlet
* is unloaded.
*/
public void destroy()
{
 super.destroy();
}
}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.