很多情況下,需要傳遞一些信息,從瀏覽器到 Web 服務(wù)器,最終到后臺(tái)程序。瀏覽器使用兩種方法可將這些信息傳遞到 Web 服務(wù)器,分別為 GET 方法和 POST 方法。
GET 方法向頁(yè)面請(qǐng)求發(fā)送已編碼的用戶信息。頁(yè)面和已編碼的信息中間用 ? 字符分隔,如下所示:
http://www.test.com/hello?key1=value1&key2=value2
GET 方法是默認(rèn)的從瀏覽器向 Web 服務(wù)器傳遞信息的方法,它會(huì)產(chǎn)生一個(gè)很長(zhǎng)的字符串,出現(xiàn)在瀏覽器的地址欄中。如果您要向服務(wù)器傳遞的是密碼或其他的敏感信息,請(qǐng)不要使用 GET 方法。GET 方法有大小限制:請(qǐng)求字符串中最多只能有 1024 個(gè)字符。
這些信息使用 QUERY_STRING 頭傳遞,并可以通過(guò) QUERY_STRING 環(huán)境變量訪問(wèn),Servlet 使用 doGet() 方法處理這種類型的請(qǐng)求。
另一個(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ù),這些數(shù)據(jù)會(huì)根據(jù)不同的情況使用不同的方法自動(dòng)解析:
getParameter():您可以調(diào)用 request.getParameter() 方法來(lái)獲取表單參數(shù)的值。
getParameterValues():如果參數(shù)出現(xiàn)一次以上,則調(diào)用該方法,并返回多個(gè)值,例如復(fù)選框。
getParameterNames():如果您想要得到當(dāng)前請(qǐng)求中的所有參數(shù)的完整列表,則調(diào)用該方法。
下面是一個(gè)簡(jiǎn)單的 URL,將使用 GET 方法向 HelloForm 程序傳遞兩個(gè)值。
http://localhost:8080/TomcatTest/HelloForm?name=菜鳥(niǎo)教程&url=www.soo66.com
下面是處理 Web 瀏覽器輸入的 HelloForm.java Servlet 程序。我們將使用 getParameter() 方法,可以很容易地訪問(wèn)傳遞的信息:
package com.nhooo.test; 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 name =new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8"); String docType = "<!DOCTYPE html> \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>站點(diǎn)名</b>:" + name + "\n" + " <li><b>網(wǎng)址</b>:" + request.getParameter("url") + "\n" + "</ul>\n" + "</body></html>"); } // 處理 POST 方法請(qǐng)求的方法 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
然后我們?cè)?web.xml 文件中創(chuàng)建以下條目:
<?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>HelloForm</servlet-name> <servlet-class>com.nhooo.test.HelloForm</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloForm</servlet-name> <url-pattern>/TomcatTest/HelloForm</url-pattern> </servlet-mapping> </web-app>
現(xiàn)在在瀏覽器的地址欄中輸入 http://localhost:8080/TomcatTest/HelloForm?name=菜鳥(niǎo)教程&url=www.soo66.com ,并在觸發(fā)上述命令之前確保已經(jīng)啟動(dòng) Tomcat 服務(wù)器。如果一切順利,您會(huì)得到下面的結(jié)果:
下面是一個(gè)簡(jiǎn)單的示例,使用 HTML 表單和提交按鈕傳遞兩個(gè)值。我們將使用相同的 Servlet HelloForm 來(lái)處理輸入。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鳥(niǎo)教程(cainiaoplus.com)</title> </head> <body> <form action="HelloForm" method="GET"> 網(wǎng)址名:<input type="text" name="name"> <br /> 網(wǎng)址:<input type="text" name="url" /> <input type="submit" value="提交" /> </form> </body> </html>
保存這個(gè) HTML 到 hello.html 文件中,目錄結(jié)構(gòu)如下所示:
嘗試輸入網(wǎng)址名和網(wǎng)址,然后點(diǎn)擊"提交"按鈕, 演示如下:
讓我們對(duì)上面的 Servlet 做小小的修改,以便它可以處理 GET 和 POST 方法。下面的 HelloForm.java Servlet 程序使用 GET 和 POST 方法處理由 Web 瀏覽器給出的輸入。
注意:如果表單提交的數(shù)據(jù)中有中文數(shù)據(jù)則需要轉(zhuǎn)碼:
String name =new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
package com.nhooo.test; 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 = "使用 POST 方法讀取表單數(shù)據(jù)"; // 處理中文 String name =new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8"); String docType = "<!DOCTYPE html> \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>站點(diǎn)名</b>:" + name + "\n" + " <li><b>網(wǎng)址</b>:" + request.getParameter("url") + "\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.html 進(jìn)行測(cè)試,如下所示:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鳥(niǎo)教程(cainiaoplus.com)</title> </head> <body> <form action="HelloForm" method="POST"> 網(wǎng)址名:<input type="text" name="name"> <br /> 網(wǎng)址:<input type="text" name="url" /> <input type="submit" value="提交" /> </form> </body> </html>
下面是上面表單的實(shí)際輸出,嘗試輸入網(wǎng)址名和網(wǎng)址,然后點(diǎn)擊"提交"按鈕,演示如下:
當(dāng)需要選擇一個(gè)以上的選項(xiàng)時(shí),則使用復(fù)選框。
下面是一個(gè) HTML 代碼示例 checkbox.html,一個(gè)帶有兩個(gè)復(fù)選框的表單。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鳥(niǎo)教程(cainiaoplus.com)</title> </head> <body> <form action="CheckBox" method="POST" target="_blank"> <input type="checkbox" name="nhooo" checked="checked" /> 菜鳥(niǎo)教程 <input type="checkbox" name="google" /> Google <input type="checkbox" name="taobao" checked="checked" /> 淘寶 <input type="submit" value="選擇站點(diǎn)" /> </form> </body> </html>
下面是 CheckBox.java Servlet 程序,處理 Web 瀏覽器給出的復(fù)選框輸入。
package com.nhooo.test; 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 CheckBox */ @WebServlet("/CheckBox") public class CheckBox extends HttpServlet { private static final long serialVersionUID = 1L; 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 = "讀取復(fù)選框數(shù)據(jù)"; String docType = "<!DOCTYPE html> \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>菜鳥(niǎo)按教程標(biāo)識(shí):</b>: " + request.getParameter("nhooo") + "\n" + " <li><b>Google 標(biāo)識(shí):</b>: " + request.getParameter("google") + "\n" + " <li><b>淘寶標(biāo)識(shí):</b>: " + request.getParameter("taobao") + "\n" + "</ul>\n" + "</body></html>"); } // 處理 POST 方法請(qǐng)求的方法 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
設(shè)置對(duì)應(yīng)的 web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>CheckBox</servlet-name> <servlet-class>com.nhooo.test.CheckBox</servlet-class> </servlet> <servlet-mapping> <servlet-name>CheckBox</servlet-name> <url-pattern>/TomcatTest/CheckBox</url-pattern> </servlet-mapping> </web-app>
上面的示例訪問(wèn)地址:http://localhost:8080/TomcatTest/checkbox.html ,查看輸出結(jié)果。
以下是通用的示例,使用 HttpServletRequest 的 getParameterNames() 方法讀取所有可用的表單參數(shù)。該方法返回一個(gè)枚舉,其中包含未指定順序的參數(shù)名。
一旦我們有一個(gè)枚舉,我們可以以標(biāo)準(zhǔn)方式循環(huán)枚舉,使用 hasMoreElements() 方法來(lái)確定何時(shí)停止,使用 nextElement() 方法來(lái)獲取每個(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>沒(mé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)在,通過(guò)下面的表單嘗試上面的 Servlet:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鳥(niǎo)教程(cainiaoplus.com)</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>
設(shè)置相應(yīng)的 web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>ReadParams</servlet-name> <servlet-class>com.nhooo.test.ReadParams</servlet-class> </servlet> <servlet-mapping> <servlet-name>ReadParams</servlet-name> <url-pattern>/TomcatTest/ReadParams</url-pattern> </servlet-mapping> </web-app>
現(xiàn)在使用上面的表單調(diào)用 Servlet,訪問(wèn)地址:http://localhost:8080/TomcatTest/test.html 查看輸出結(jié)果。
您可以嘗試使用上面的 Servlet 來(lái)讀取其他的表單數(shù)據(jù),比如文本框、單選按鈕或下拉框等。