表單數(shù)據(jù)

2018-08-12 21:19 更新

表單數(shù)據(jù)

當你需要從瀏覽器到 Web 服務器傳遞一些信息并最終傳回到后臺程序時,你一定遇到了許多情況。瀏覽器使用兩種方法向 Web 服務器傳遞信息。這些方法是 GET 方法和 POST 方法。

GET 方法

GET 方法向頁面請求發(fā)送已編碼的用戶信息。頁面和已編碼的信息用 ? 字符分隔,如下所示:

http://www.test.com/hello?key1=value1&key2=value2

GET 方法是從瀏覽器向 web 服務器傳遞信息的默認的方法,且它會在你的瀏覽器的地址欄中產(chǎn)生一個很長的字符串。如果你向服務器傳遞密碼或其他敏感信息,請不要使用 GET 方法。GET 方法有大小限制:請求字符串中最多只能有 1024 個字符。

這些信息使用 QUERY_STRING 頭傳遞,并通過 QUERY_STRING 環(huán)境變量訪問,Servlet 使用 doGet() 方法處理這種類型的請求。

POST 方法

一般情況下,將信息傳遞給后臺程序的一種更可靠的方法是 POST 方法。POST 方法打包信息的方式與 GET 方法相同,但是 POST 方法不是把信息作為 URL 中 ? 字符之后的文本字符串進行發(fā)送,而是把它作為一個單獨的消息發(fā)送。消息以標準輸出的形式傳到后臺程序,你可以在你的處理過程中解析并使用這些標準輸出。Servlet 使用 doPost() 方法處理這種類型的請求。

使用 Servlet 讀取表單數(shù)據(jù)

Servlet 以自動解析的方式處理表單數(shù)據(jù),根據(jù)不同的情況使用如下不同的方法:

  • getParameter():你可以調用 request.getParameter() 方法來獲取表單參數(shù)的值。

  • getParameterValues():如果參數(shù)出現(xiàn)不止一次,那么調用該方法并返回多個值,例如復選框。

  • getParameterNames():如果你想要得到一個當前請求的所有參數(shù)的完整列表,那么調用該方法。

使用 URL 的 GET 方法實例

這是一個簡單的 URL,使用 GET 方法將兩個值傳遞給 HelloForm 程序。

http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI

下面是 HelloForm.java servlet 程序,處理由 web 瀏覽器給定的輸入。我們將使用 getParameter() 方法,使訪問傳遞的信息變得非常容易:

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloForm extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      String title = "Using GET Method to Read Form Data";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" +
                "<h1 align=\"center\">" + title + "</h1>\n" +
                "<ul>\n" +
                "  <li><b>First Name</b>: "
                + request.getParameter("first_name") + "\n" +
                "  <li><b>Last Name</b>: "
                + request.getParameter("last_name") + "\n" +
                "</ul>\n" +
                "</body></html>");
  }
}

假設你的環(huán)境已經(jīng)正確地設置,編譯 HelloForm.java,如下所示:

$ javac HelloForm.java

如果一切順利,上述編譯會產(chǎn)生 HelloForm.class 文件。接下來,你需要把這個類文件復制到 <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes 中,并在 <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/ 中的 web.xml 文件中創(chuàng)建以下條目:

    <servlet>
        <servlet-name>HelloForm</servlet-name>
        <servlet-class>HelloForm</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloForm</servlet-name>
        <url-pattern>/HelloForm</url-pattern>
    </servlet-mapping>

現(xiàn)在在你瀏覽器的地址欄中輸入 http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI,并在瀏覽器中觸發(fā)上述命令之前,確保你已經(jīng)啟動 Tomcat 服務器。這將產(chǎn)生如下所示的結果:

Using GET Method to Read Form Data

使用表單的 GET 方法實例

下面是一個簡單的實例,使用 HTML 表單和提交按鈕傳遞兩個值。我們將使用相同的 Servlet HelloForm 來處理這個輸入。

<html>
<body>
<form action="HelloForm" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

將這個 HTML 保存到 hello.htm 文件中,并把它放在 <Tomcat-installation-directory>/webapps/ROOT 目錄下。當你訪問 http://localhost:8080/Hello.htm 時,下面是上述表單的實際輸出。

First Name: Last Name:

嘗試輸入姓名,然后點擊提交按鈕來在 tomcat 運行的本地計算機上查看結果。基于提供的輸入,它會產(chǎn)生與上述例子中相似的結果。

使用表單的 POST 方法實例

讓我們對上述 servlet 做一點修改,以便它可以處理 GET 方法和 POST 方法。下面是 HelloForm.java servlet 程序,使用 GET 和 POST 方法處理由 web 瀏覽器給出的輸入。

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloForm extends HttpServlet {
  // Method to handle GET method request.
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      String title = "Using GET Method to Read Form Data";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" +
                "<h1 align=\"center\">" + title + "</h1>\n" +
                "<ul>\n" +
                "  <li><b>First Name</b>: "
                + request.getParameter("first_name") + "\n" +
                "  <li><b>Last Name</b>: "
                + request.getParameter("last_name") + "\n" +
                "</ul>\n" +
                "</body></html>");
  }
  // Method to handle POST method request.
  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
     doGet(request, response);
  }
}

現(xiàn)在編譯,部署上述 Servlet,并使用帶有 POST 方法的 Hello.htm 測試它,如下所示:

<html>
<body>
<form action="HelloForm" method="POST">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

這是上述表單的實際輸出,嘗試輸入姓名,然后點擊提交按鈕,在 tomcat 運行的本地計算機上查看結果。

First Name: Last Name:

基于提供的輸入,它會產(chǎn)生與上述例子中相似的結果。

將復選框數(shù)據(jù)傳遞到 Servlet 程序

當要選擇多個選項時,就要使用復選框。

這是一個 HTML 代碼實例,CheckBox.htm,一個表單帶有兩個復選框。

<html>
<body>
<form action="CheckBox" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> Maths
<input type="checkbox" name="physics"  /> Physics
<input type="checkbox" name="chemistry" checked="checked" /> 
                                                Chemistry
<input type="submit" value="Select Subject" />
</form>
</body>
</html>

這段代碼的結果是如下所示的表單:

Maths Physics Chemistry

下面是 CheckBox.java servlet 程序,來為復選框按鈕處理 web 瀏覽器給定的輸入。

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class CheckBox extends HttpServlet {
  // Method to handle GET method request.
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      String title = "Reading Checkbox Data";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" +
                "<h1 align=\"center\">" + title + "</h1>\n" +
                "<ul>\n" +
                "  <li><b>Maths Flag : </b>: "
                + request.getParameter("maths") + "\n" +
                "  <li><b>Physics Flag: </b>: "
                + request.getParameter("physics") + "\n" +
                "  <li><b>Chemistry Flag: </b>: "
                + request.getParameter("chemistry") + "\n" +
                "</ul>\n" +
                "</body></html>");
  }
  // Method to handle POST method request.
  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
     doGet(request, response);
  }
}

上面的實例將顯示如下所示結果:

Reading Checkbox Data

讀取所有的表單參數(shù)

以下是使用 HttpServletRequest 的 getParameterNames() 方法的通用實例來讀取所有可用的表單參數(shù)。該方法返回一個枚舉,包含了未指定順序的參數(shù)名稱。

一旦我們得到一個枚舉,我們可以以標準方式循環(huán)這個枚舉,使用 hasMoreElements() 方法來確定何時停止循環(huán),使用 nextElement() 方法來獲取每個參數(shù)的名稱。

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// Extend HttpServlet class
public class ReadParams extends HttpServlet {
  // Method to handle GET method request.
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      String title = "Reading All Form Parameters";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
        "<html>\n" +
        "<head><title>" + title + "</title></head>\n" +
        "<body bgcolor=\"#f0f0f0\">\n" +
        "<h1 align=\"center\">" + title + "</h1>\n" +
        "<table width=\"100%\" border=\"1\" align=\"center\">\n" +
        "<tr bgcolor=\"#949494\">\n" +
        "<th>Param Name</th><th>Param Value(s)</th>\n"+
        "</tr>\n");
      Enumeration paramNames = request.getParameterNames();      
      while(paramNames.hasMoreElements()) {
         String paramName = (String)paramNames.nextElement();
         out.print("<tr><td>" + paramName + "</td>\n<td>");
         String[] paramValues =
                request.getParameterValues(paramName);
         // Read single valued data
         if (paramValues.length == 1) {
           String paramValue = paramValues[0];
           if (paramValue.length() == 0)
             out.println("<i>No Value</i>");
           else
             out.println(paramValue);
         } else {
             // Read multiple valued data
             out.println("<ul>");
             for(int i=0; i < paramValues.length; i++) {
                out.println("<li>" + paramValues[i]);
             }
             out.println("</ul>");
         }
      }
      out.println("</tr>\n</table>\n</body></html>");
  }
  // Method to handle POST method request.
  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
     doGet(request, response);
  }
}

現(xiàn)在,用下面的表單嘗試上述 servlet:

<html>
<body>
<form action="ReadParams" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> Maths
<input type="checkbox" name="physics"  /> Physics
<input type="checkbox" name="chemistry" checked="checked" /> Chem
<input type="submit" value="Select Subject" />
</form>
</body>
</html>

現(xiàn)在使用上述表單調用 servlet 將產(chǎn)生如下所示結果:

Reading All Form Parameters

你可以嘗試使用上述 servlet 來讀取有其他對象的其他表單數(shù)據(jù),比如文本框、單選按鈕或下拉框等。

以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號