Servlet 表單數據
很多情況下,需要傳遞一些信息,從瀏覽器到Web 服務器,最終到後台程序。 瀏覽器使用兩種方法可將這些信息傳遞到Web 服務器,分別為GET 方法和POST 方法。
GET 方法
GET 方法向頁面請求發送已編碼的用戶信息。 頁面和已編碼的信息中間用? 字符分隔,如下所示:
http://www.test.com/hello?key1=value1&key2=value2
GET 方法是默認的從瀏覽器向Web 服務器傳遞信息的方法,它會產生一個很長的字符串,出現在瀏覽器的地址欄中。 如果您要向服務器傳遞的是密碼或其他的敏感信息,請不要使用GET 方法。 GET 方法有大小限制:請求字符串中最多只能有1024 個字符。
這些信息使用QUERY_STRING頭傳遞,並可以通過QUERY_STRING環境變量訪問,Servlet使用doGet()方法處理這種類型的請求。
POST 方法
另一個向後台程序傳遞信息的比較可靠的方法是POST 方法。 POST 方法打包信息的方式與GET 方法基本相同,但是POST 方法不是把信息作為URL 中? 字符後的文本字符串進行發送,而是把這些信息作為一個單獨的消息。 消息以標準輸出的形式傳到後台程序,您可以解析和使用這些標準輸出。 Servlet 使用doPost() 方法處理這種類型的請求。
使用Servlet 讀取表單數據
Servlet 處理表單數據,這些數據會根據不同的情況使用不同的方法自動解析:
- getParameter():您可以調用request.getParameter()方法來獲取表單參數的值。
- getParameterValues():如果參數出現一次以上,則調用該方法,並返回多個值,例如復選框。
- getParameterNames():如果您想要得到當前請求中的所有參數的完整列表,則調用該方法。
使用URL 的GET 方法實例
下面是一個簡單的URL,將使用GET 方法向HelloForm 程序傳遞兩個值。
http://localhost:8080/TomcatTest/HelloForm?name=本教程&url=www.w3big.com
下面是處理Web瀏覽器輸入的HelloForm.java Servlet程序。 我們將使用getParameter()方法,可以很容易地訪問傳遞的信息:
package com.w3big.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 { // 设置响应内容类型 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String title = "使用 GET 方法读取表单数据"; // 处理中文 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>站点名</b>:" + name + "\n" + " <li><b>网址</b>:" + request.getParameter("url") + "\n" + "</ul>\n" + "</body></html>"); } // 处理 POST 方法请求的方法 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }然後我們在web.xml文件中創建以下條目:
<?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>HelloForm</servlet-name> <servlet-class>com.w3big.test.HelloForm</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloForm</servlet-name> <url-pattern>/TomcatTest/HelloForm</url-pattern> </servlet-mapping> </web-app>
現在在瀏覽器的地址欄中輸入http://localhost:8080/TomcatTest/HelloForm?name=本教程&url=www.w3big.com ,並在觸發上述命令之前確保已經啟動Tomcat服務器。 如果一切順利,您會得到下面的結果:
使用表單的GET 方法實例
下面是一個簡單的實例,使用HTML 表單和提交按鈕傳遞兩個值。 我們將使用相同的Servlet HelloForm 來處理輸入。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>本教程(w3big.com)</title> </head> <body> <form action="HelloForm" method="GET"> 网址名:<input type="text" name="name"> <br /> 网址:<input type="text" name="url" /> <input type="submit" value="提交" /> </form> </body> </html>
保存這個HTML 到hello.html 文件中,目錄結構如下所示:
嘗試輸入網址名和網址,然後點擊"提交"按鈕,Gif 演示如下:
使用表單的POST 方法實例
讓我們對上面的Servlet 做小小的修改,以便它可以處理GET 和POST 方法。 下面的HelloForm.java Servlet程序使用GET和POST方法處理由Web瀏覽器給出的輸入。
注意:如果表單提交的數據中有中文數據則需要轉碼:
String name =new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
package com.w3big.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 { // 设置响应内容类型 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String title = "使用 POST 方法读取表单数据"; // 处理中文 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>站点名</b>:" + name + "\n" + " <li><b>网址</b>:" + request.getParameter("url") + "\n" + "</ul>\n" + "</body></html>"); } // 处理 POST 方法请求的方法 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
現在,編譯部署上述的Servlet,並使用帶有POST 方法的hello.html 進行測試,如下所示:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>本教程(w3big.com)</title> </head> <body> <form action="HelloForm" method="POST"> 网址名:<input type="text" name="name"> <br /> 网址:<input type="text" name="url" /> <input type="submit" value="提交" /> </form> </body> </html>
下面是上面表單的實際輸出,嘗試輸入網址名和網址,然後點擊"提交"按鈕,Gif 演示如下:
將復選框數據傳遞到Servlet 程序
當需要選擇一個以上的選項時,則使用複選框。
下面是一個HTML 代碼實例checkbox.html,一個帶有兩個複選框的表單。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>本教程(w3big.com)</title> </head> <body> <form action="CheckBox" method="POST" target="_blank"> <input type="checkbox" name="w3big" checked="checked" /> 本教程 <input type="checkbox" name="google" /> Google <input type="checkbox" name="taobao" checked="checked" /> 淘宝 <input type="submit" value="选择站点" /> </form> </body> </html>
下面是CheckBox.java Servlet 程序,處理Web 瀏覽器給出的複選框輸入。
package com.w3big.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 { // 设置响应内容类型 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String title = "读取复选框数据"; 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>本按教程标识:</b>: " + request.getParameter("w3big") + "\n" + " <li><b>Google 标识:</b>: " + request.getParameter("google") + "\n" + " <li><b>淘宝标识:</b>: " + request.getParameter("taobao") + "\n" + "</ul>\n" + "</body></html>"); } // 处理 POST 方法请求的方法 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
設置對應的web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>CheckBox</servlet-name> <servlet-class>com.w3big.test.CheckBox</servlet-class> </servlet> <servlet-mapping> <servlet-name>CheckBox</servlet-name> <url-pattern>/TomcatTest/CheckBox</url-pattern> </servlet-mapping> </web-app>
上面的實例將顯示下面的結果:
讀取所有的表單參數
以下是通用的實例,使用HttpServletRequest的getParameterNames()方法讀取所有可用的表單參數。 該方法返回一個枚舉,其中包含未指定順序的參數名。
一旦我們有一個枚舉,我們可以以標準方式循環枚舉,使用hasMoreElements()方法來確定何時停止,使用nextElement()方法來獲取每個參數的名稱。
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 { // 设置响应内容类型 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String title = "读取所有的表单数据"; 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>参数名称</th><th>参数值</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); // 读取单个值的数据 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 { // 读取多个值的数据 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); } }
現在,通過下面的表單嘗試上面的Servlet:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>本教程(w3big.com)</title> </head> <body> <form action="ReadParams" method="POST" target="_blank"> <input type="checkbox" name="maths" checked="checked" /> 数学 <input type="checkbox" name="physics" /> 物理 <input type="checkbox" name="chemistry" checked="checked" /> 化学 <input type="submit" value="选择学科" /> </form> </body> </html>
設置相應的web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>ReadParams</servlet-name> <servlet-class>com.w3big.test.ReadParams</servlet-class> </servlet> <servlet-mapping> <servlet-name>ReadParams</servlet-name> <url-pattern>/TomcatTest/ReadParams</url-pattern> </servlet-mapping> </web-app>
現在使用上面的表單調用Servlet,將產生以下結果:
您可以嘗試使用上面的Servlet 來讀取其他的表單數據,比如文本框、單選按鈕或下拉框等。