亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Grundlegendes Servlet-Tutorial / Servlet 表單數(shù)據(jù)

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

很多情況下,需要傳遞一些信息,從瀏覽器到 Web 服務(wù)器,最終到后臺(tái)程序。瀏覽器使用兩種方法可將這些信息傳遞到 Web 服務(wù)器,分別為 GET 方法和 POST 方法。

GET 方法

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

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

GET 方法是默認(rèn)的從瀏覽器向 Web 服務(wù)器傳遞信息的方法,它會(huì)產(chǎn)生一個(gè)很長的字符串,出現(xiàn)在瀏覽器的地址欄中。如果您要向服務(wù)器傳遞的是密碼或其他的敏感信息,請(qǐng)不要使用 GET 方法。GET 方法有大小限制:請(qǐng)求字符串中最多只能有 1024 個(gè)字符。

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

POST 方法

另一個(gè)向后臺(tái)程序傳遞信息的比較可靠的方法是 POST 方法。POST 方法打包信息的方式與 GET 方法基本相同,但是 POST 方法不是把信息作為 URL 中 ? 字符后的文本字符串進(jìn)行發(fā)送,而是把這些信息作為一個(gè)單獨(dú)的消息。消息以標(biāo)準(zhǔn)輸出的形式傳到后臺(tái)程序,您可以解析和使用這些標(biāo)準(zhǔn)輸出。Servlet 使用 doPost() 方法處理這種類型的請(qǐng)求。

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

Servlet 處理表單數(shù)據(jù),這些數(shù)據(jù)會(huì)根據(jù)不同的情況使用不同的方法自動(dòng)解析:

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

  • getParameterValues():如果參數(shù)出現(xiàn)一次以上,則調(diào)用該方法,并返回多個(gè)值,例如復(fù)選框。

  • getParameterNames():如果您想要得到當(dāng)前請(qǐng)求中的所有參數(shù)的完整列表,則調(diào)用該方法。

使用 URL 的 GET 方法實(shí)例

下面是一個(gè)簡單的 URL,將使用 GET 方法向 HelloForm 程序傳遞兩個(gè)值。

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

下面是處理 Web 瀏覽器輸入的 HelloForm.java Servlet 程序。我們將使用 getParameter()  方法,可以很容易地訪問傳遞的信息:

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloForm
 */
@WebServlet("/HelloForm")
public class HelloForm extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloForm() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 設(shè)置響應(yīng)內(nèi)容類型
		response.setContentType("text/html;charset=UTF-8");

		PrintWriter out = response.getWriter();
		String title = "使用 GET 方法讀取表單數(shù)據(jù)";
		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>名字</b>:"
		    + request.getParameter("first_name") + "\n" +
		    "  <li><b>姓氏</b>:"
		    + request.getParameter("last_name") + "\n" +
		    "</ul>\n" +
		    "</body></html>");
	}

}

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

$ javac HelloForm.java

如果一切順利,上述編譯會(huì)產(chǎn)生 HelloForm.class 文件。接下來,您就必須把該類文件復(fù)制到 <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)啟動(dòng) Tomcat 服務(wù)器。如果一切順利,您會(huì)得到下面的結(jié)果:

使用 GET 方法讀取表單數(shù)據(jù)

  • 名字:ZARA

  • 姓氏:ALI

使用表單的 GET 方法實(shí)例

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

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文網(wǎng)(php.cn)</title>
</head>
<body>
<form action="HelloForm" method="GET">
名字:<input type="text" name="first_name">
<br />
姓氏:<input type="text" name="last_name" />
<input type="submit" value="提交" />
</form>
</body>
</html>

保存這個(gè) HTML 到 hello.htm 文件中,并把它放在 <Tomcat-installation-directory>/webapps/ROOT 目錄下。當(dāng)您訪問 http://localhost:8080/Hello.htm 時(shí),下面是上面表單的實(shí)際輸出。

嘗試輸入名字和姓氏,然后點(diǎn)擊"提交"按鈕,在您本機(jī)上查看輸出結(jié)果?;谒峁┑妮斎耄鼤?huì)產(chǎn)生與上一個(gè)實(shí)例類似的結(jié)果。

使用表單的 POST 方法實(shí)例

讓我們對(duì)上面的 Servlet 做小小的修改,以便它可以處理 GET 和 POST 方法。下面的 HelloForm.java Servlet 程序使用 GET 和 POST 方法處理由 Web 瀏覽器給出的輸入。

// 導(dǎo)入必需的 java 庫
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// 擴(kuò)展 HttpServlet 類
public class HelloForm extends HttpServlet {
 
  // 處理 GET 方法請(qǐng)求的方法
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // 設(shè)置響應(yīng)內(nèi)容類型
      response.setContentType("text/html;charset=UTF-8");

      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>名字</b>:"
                + request.getParameter("first_name") + "\n" +
                "  <li><b>姓氏</b>:"
                + request.getParameter("last_name") + "\n" +
                "</ul>\n" +
                "</body></html>");
  }
  // 處理 POST 方法請(qǐng)求的方法
  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
     doGet(request, response);
  }
}

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

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文網(wǎng)(php.cn)</title>
</head>
<body>
<form action="HelloForm" method="POST">
名字:<input type="text" name="first_name">
<br />
姓氏:<input type="text" name="last_name" />
<input type="submit" value="提交" />
</form>
</body>
</html>

下面是上面表單的實(shí)際輸出,嘗試輸入名字和姓氏,然后點(diǎn)擊"提交"按鈕,在您本機(jī)上查看輸出結(jié)果。

基于所提供的輸入,它會(huì)產(chǎn)生與上一個(gè)實(shí)例類似的結(jié)果。

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

當(dāng)需要選擇一個(gè)以上的選項(xiàng)時(shí),則使用復(fù)選框。

下面是一個(gè) HTML 代碼實(shí)例 CheckBox.htm,一個(gè)帶有兩個(gè)復(fù)選框的表單。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文網(wǎng)(php.cn)</title>
</head>
<body>
<form action="CheckBox" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> 數(shù)學(xué)
<input type="checkbox" name="physics"  /> 物理
<input type="checkbox" name="chemistry" checked="checked" /> 
                                                化學(xué)
<input type="submit" value="選擇學(xué)科" />
</form>
</body>
</html>

這段代碼的結(jié)果是下面的表單:

下面是 CheckBox.java Servlet 程序,處理 Web 瀏覽器給出的復(fù)選框輸入。

// 導(dǎo)入必需的 java 庫
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// 擴(kuò)展 HttpServlet 類
public class CheckBox extends HttpServlet {
 
  // 處理 GET 方法請(qǐng)求的方法
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // 設(shè)置響應(yīng)內(nèi)容類型
      response.setContentType("text/html;charset=UTF-8");

      PrintWriter out = response.getWriter();
	  String title = "讀取復(fù)選框數(shù)據(jù)";
      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>數(shù)學(xué)標(biāo)識(shí):</b>: "
                + request.getParameter("maths") + "\n" +
                "  <li><b>物理標(biāo)識(shí):</b>: "
                + request.getParameter("physics") + "\n" +
                "  <li><b>化學(xué)標(biāo)識(shí):</b>: "
                + request.getParameter("chemistry") + "\n" +
                "</ul>\n" +
                "</body></html>");
  }
  // 處理 POST 方法請(qǐng)求的方法
  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
     doGet(request, response);
  }
}

上面的實(shí)例將顯示下面的結(jié)果:

讀取復(fù)選框數(shù)據(jù)

  • 數(shù)學(xué)標(biāo)識(shí):on

  • 物理標(biāo)識(shí):null

  • 化學(xué)標(biāo)識(shí):on

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

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

一旦我們有一個(gè)枚舉,我們可以以標(biāo)準(zhǔn)方式循環(huán)枚舉,使用 hasMoreElements() 方法來確定何時(shí)停止,使用 nextElement() 方法來獲取每個(gè)參數(shù)的名稱。

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ReadParams
 */
@WebServlet("/ReadParams")
public class ReadParams extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ReadParams() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 設(shè)置響應(yīng)內(nèi)容類型
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String title = "讀取所有的表單數(shù)據(jù)";
		String docType =
			"<!doctype html public \"-//w3c//dtd html 4.0 " +
			"transitional//en\">\n";
			out.println(docType +
			"<html>\n" +
			"<head><meta charset=\"utf-8\"><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>參數(shù)名稱</th><th>參數(shù)值</th>\n"+
			"</tr>\n");

		Enumeration paramNames = request.getParameterNames();

		while(paramNames.hasMoreElements()) {
			String paramName = (String)paramNames.nextElement();
			out.print("<tr><td>" + paramName + "</td>\n");
			String[] paramValues =
			request.getParameterValues(paramName);
			// 讀取單個(gè)值的數(shù)據(jù)
			if (paramValues.length == 1) {
				String paramValue = paramValues[0];
				if (paramValue.length() == 0)
					out.println("<td><i>沒有值</i></td>");
				else
					out.println("<td>" + paramValue + "</td>");
			} else {
				// 讀取多個(gè)值的數(shù)據(jù)
				out.println("<td><ul>");
				for(int i=0; i < paramValues.length; i++) {
				out.println("<li>" + paramValues[i]);
			}
				out.println("</ul></td>");
			}
			out.print("</tr>");
		}
		out.println("\n</table>\n</body></html>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

現(xiàn)在,通過下面的表單嘗試上面的 Servlet:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文網(wǎng)(php.cn)</title>
</head>
<body>

<form action="ReadParams" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> 數(shù)學(xué)
<input type="checkbox" name="physics"  /> 物理
<input type="checkbox" name="chemistry" checked="checked" /> 化學(xué)
<input type="submit" value="選擇學(xué)科" />
</form>

</body>
</html>

現(xiàn)在使用上面的表單調(diào)用 Servlet,將產(chǎn)生以下結(jié)果:

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