程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA編程入門知識 >> Java Servlet編程及應用之五

Java Servlet編程及應用之五

編輯:JAVA編程入門知識

       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();
}
}
 
  注意:Cookie 進行服務器端與客戶端的雙向交流,所以它涉及到安全性問題。
 

  使用Java Servlet API 進行會話管理

  javax.servlet.http.HttpSession 接口封裝了HTTP 會話的細節,該會話與一段時間內特定的Web 客戶對Web 服務器的多個請求相關。管理會話數據主要涉及到3個方面:會話交換、會話重定位和會話持久性,只有實現了java.io.Serializable 接口的數據對象才能夠被交換、重定位和保持。這個接口主要是讓對象具有序列化的能力,它可以將對象的狀態信息寫入任意的輸出流中如:文件、網絡連接等。

  編程思路:下面是實現一個簡單在商場購物的例子,當用戶選購商品(糖果、收音機和練習簿)放入購物袋中,保存選購的商品信息。

  ShowBuy.java 的源代碼如下:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class ShowBuy extends HttpServlet
{
 public void doGet(HttpServletRequest req, HttpServletResponse res)
 throws ServletException, java.io.IOException
 {
  String[] item={"糖果","收音機","練習簿"};
  //獲取會話對象
  HttpSession session=req.getSession(true);
  //獲取選擇的商品數目
  Integer itemCount=(Interger) session.getValue("itemCount");
  //如果沒放入商品則數目為0
  if (itemCount==null){
   itemCount=new Integer(0);
  }

  // Set the content type of the response
  res.setContentType("text/html;charset=gb2312");
  PrintWriter out=res.getWriter();

  //取得POST上來的表單信息
  String[] itemsSelected;
  String itemName;
  itemsSelected=req.getParameterValues("item");
  //將選中的商品放入會話對象
  if(itemsSelected !=null){
   for(int i=0;i<itemsSelected.length;i++){
    itemName=itemsSelected[i];
    itemCount=new Integer(itemCount.intValue()+1);
    session.putValue("Item" + itemCount,itemName);
    //將商品名稱定義為ItemX
    session.putValue("itemCount",itemCount);
    //將商品數量放入會話對象
   }
  }

  // Write the page header
  out.println("<html>");
  out.println("<head>");
  out.println("<title>購物袋的內容</title>");
  out.println("</head>");
  out.println("<body>");
  out.println("<center><h1>你放在購物袋中的商品是: </h1></center>");
  //將購物袋的內容寫入頁面
  for (int i = 1; i < itemCount.intValue(); i++) {
   String item =(String) session.getValue("Item"+i);
   //取出商品名稱
   out.println(items[Integer.parseInt(item)]);
   out.println("<BR>");
  }
  // Wrap up
  out.println("</body>");
  out.println("</html>");
  out.close();
 }
}
  客戶端的ShowBuy.html 的源代碼如下:

<HTML>
<HEAD>
 <TITLE>購物袋的實例 </TITLE>
</HEAD>
<BODY>
 <CENTER><H1>百貨商場</H1></CENTER>
 <HR>
 <FORM ACTION='servlet/ShowBuy" METHOD="POST">
  選購商品
  <p><INPUT TYPE="Checkbox" NAME="item" VALUE="0">
   第一種:糖果</p>
  <p><INPUT TYPE="Checkbox" NAME="item" VALUE="1">
   第二種:收音機</p>
  <p><INPUT TYPE="Checkbox" NAME="item" VALUE="2">
   第三種:練習簿</p>
  <HR>
  <INPUT TYPE="Submit" NAME="bt_submit" VALUE="加入購物袋">
 </FORM>
</BODY>
</HTML>
  編程技巧說明:

  在Servlet 中進行會話管理時,首先要獲得會話對象。HttpServletRequest.getSession()對象返回與請求相關的當前HttpSession 對象,並且當該對象不存在時就新創建一個對象;HttpServletRequest.getSession(true)實現相同的功能。如果參數是false,當不存在會話對象時,將返回一個null 值。

//獲取會話對象
HttpSession session=req.getSession(true);
//獲取選擇的商品數目
Integer itemCount=(Interger) session.getValue("itemCount");
  具體操作時,當用戶選擇商品後,單擊“加入購物袋"按鈕,Servlet 輸出用戶選擇的商品。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved