Servlet 表单数据
很多情況下,需要傳遞一些信息,從瀏覽器到 Web 服務器,最終到后臺程序。瀏覽器使用兩種方法可將這些信息傳遞到 Web 服務器,分別為 GET 方法和 POST 方法。
GET 方法
GET 方法向頁面請求發送已編碼的用戶信息。頁面和已編碼的信息中間用 ? 字符分隔,如下所示:
http://www.test.com/hello?key1=value1&key2=value2GET 方法是默認的從瀏覽器向 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.runoob.com
下面是處理 Web 瀏覽器輸入的 HelloForm.java Servlet 程序。我們將使用 getParameter() 方法,可以很容易地訪問傳遞的信息:
package com.runoob.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.runoob.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.runoob.com ,并在觸發上述命令之前確保已經啟動 Tomcat 服務器。如果一切順利,您會得到下面的結果:
使用表單的 GET 方法實例
下面是一個簡單的實例,使用 HTML 表單和提交按鈕傳遞兩個值。我們將使用相同的 Servlet HelloForm 來處理輸入。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鳥教程(runoob.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.runoob.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>菜鳥教程(runoob.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>菜鳥教程(runoob.com)</title> </head> <body> <form action="CheckBox" method="POST" target="_blank"> <input type="checkbox" name="runoob" 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.runoob.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("runoob") + "\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.runoob.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>");elseout.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 stubdoGet(request, response);}}現在,通過下面的表單嘗試上面的 Servlet:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鳥教程(runoob.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.runoob.test.ReadParams</servlet-class></servlet><servlet-mapping><servlet-name>ReadParams</servlet-name><url-pattern>/TomcatTest/ReadParams</url-pattern></servlet-mapping> </web-app>現在使用上面的表單調用 Servlet,將產生以下結果:
您可以嘗試使用上面的 Servlet 來讀取其他的表單數據,比如文本框、單選按鈕或下拉框等。
總結
以上是生活随笔為你收集整理的Servlet 表单数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js里面格式化日期
- 下一篇: Linux命令学习总结:dos2unix