Servlets 简明教程
Servlets - Form Data
您一定遇到过许多情况,需要将某些信息从浏览器传递到 Web 服务器,最终传递到您的后端程序。浏览器使用两种方法将此信息传递给 Web 服务器。这些方法是 GET 方法和 POST 方法。
You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your backend program. The browser uses two methods to pass this information to web server. These methods are GET Method and POST Method.
GET Method
GET 方法将编码后的用户信息附加到页面请求中发送。页面和编码后的信息通过 ? (问号)符号分隔,如下所示 -
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? (question mark) symbol as follows −
http://www.test.com/hello?key1 = value1&key2 = value2
GET 方法是将信息从浏览器传递到 Web 服务器的默认方法,它生成一个长字符串,显示在浏览器的 Location:box 中。如果您有密码或其他敏感信息要传递给服务器,切勿使用 GET 方法。GET 方法有大小限制:仅能在请求字符串中使用 1024 个字符。
The GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser’s Location:box. Never use the GET method if you have password or other sensitive information to pass to the server. The GET method has size limitation: only 1024 characters can be used in a request string.
此信息使用 QUERY_STRING 标头传递,并且可以通过 QUERY_STRING 环境变量访问,并且 Servlet 使用 doGet() 方法处理此类请求。
This information is passed using QUERY_STRING header and will be accessible through QUERY_STRING environment variable and Servlet handles this type of requests using doGet() method.
POST Method
一种通常更可靠的将信息传递到后端程序的方法是 POST 方法。此方法以与 GET 方法完全相同的方式打包信息,但它不是在 URL 中的 ?(问号)后面作为文本字符串发送,而是作为一条单独的消息发送。此消息以标准输入的形式到达后端程序,您可以对其进行解析并用于处理。Servlet 使用 doPost() 方法处理此类请求。
A generally more reliable method of passing information to a backend program is the POST method. This packages the information in exactly the same way as GET method, but instead of sending it as a text string after a ? (question mark) in the URL it sends it as a separate message. This message comes to the backend program in the form of the standard input which you can parse and use for your processing. Servlet handles this type of requests using doPost() method.
Reading Form Data using Servlet
Servlet 根据情况使用以下方法自动处理表单数据解析 -
Servlets handles form data parsing automatically using the following methods depending on the situation −
-
getParameter() − You call request.getParameter() method to get the value of a form parameter.
-
getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox.
-
getParameterNames() − Call this method if you want a complete list of all parameters in the current request.
GET Method Example using URL
这是一个简单的 URL,它将使用 GET 方法将两个值传递给 HelloForm 程序。
Here is a simple URL which will pass two values to HelloForm program using GET method.
下面是 HelloForm.java servlet 程序来处理 web 浏览器给定的输入。我们准备使用 getParameter() 方法,该方法使得访问传递的信息变得非常容易 −
Given below is the HelloForm.java servlet program to handle input given by web browser. We are going to use getParameter() method which makes it very easy to access passed information −
// 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>"
);
}
}
假设您的环境已正确设置,请按以下方式编译 HelloForm.java −
Assuming your environment is set up properly, compile HelloForm.java as follows −
$ javac HelloForm.java
如果一切顺利,上面的编译会生成 HelloForm.class 文件。接下来您需要将此类文件复制到 <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes 并创建以下条目,该条目位于 <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
If everything goes fine, above compilation would produce HelloForm.class file. Next you would have to copy this class file in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes and create following entries in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
<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>
现在在浏览器的“位置:”框中键入 [role="bare"] [role="bare"]http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI ,在浏览器中执行上述命令之前,请确保您已经启动了 tomcat 服务器。这将生成以下结果 −
Now type [role="bare"]http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI in your browser’s Location:box and make sure you already started tomcat server, before firing above command in the browser. This would generate following result −
Using GET Method to Read Form Data
First Name: ZARA
Last Name: ALI
GET Method Example Using Form
这是一个简单的示例,它使用 HTML FORM 和提交按钮传递两个值。我们将使用相同的 Servlet HelloForm 来处理此输入。
Here is a simple example which passes two values using HTML FORM and submit button. We are going to use same Servlet HelloForm to handle this input.
<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-installationdirectory>/webapps/ROOT 目录中。当您访问 [role="bare"] [role="bare"]http://localhost:8080/Hello.htm 时,以下就是上述表单的实际输出。
Keep this HTML in a file Hello.htm and put it in <Tomcat-installationdirectory>/webapps/ROOT directory. When you would access [role="bare"]http://localhost:8080/Hello.htm, here is the actual output of the above form.
尝试输入名字和姓氏,然后单击提交按钮,以查看 tomcat 运行的本地计算机上的结果。根据提供的输入,它将生成类似于上述示例中提到的结果。
Try to enter First Name and Last Name and then click submit button to see the result on your local machine where tomcat is running. Based on the input provided, it will generate similar result as mentioned in the above example.
POST Method Example Using Form
让我们对上述 servlet 进行一点修改,以便它可以处理 GET 和 POST 方法。以下是 HelloForm.java servlet 程序来处理使用 GET 或 POST 方法由 web 浏览器给定的输入。
Let us do little modification in the above servlet, so that it can handle GET as well as POST methods. Below is HelloForm.java servlet program to handle input given by web browser using GET or POST methods.
// 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);
}
}
现在编译并部署上述 Servlet,并使用 Hello.htm 对其进行测试,方法如下 −
Now compile and deploy the above Servlet and test it using Hello.htm with the POST method as follows −
<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 运行的本地计算机上的结果。
Here is the actual output of the above form, Try to enter First and Last Name and then click submit button to see the result on your local machine where tomcat is running.
基于提供的输入,它将生成类似于上述示例中提到的结果。
Based on the input provided, it would generate similar result as mentioned in the above examples.
Passing Checkbox Data to Servlet Program
如果要求选择多个选项,则使用复选框。
Checkboxes are used when more than one option is required to be selected.
这是一个带两个复选框的表单的 HTML 代码示例,CheckBox.htm
Here is example HTML code, CheckBox.htm, for a form with two checkboxes
<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>
此代码的结果是以下表单
The result of this code is the following form
下面是 CheckBox.java servlet 程序来处理复选框按钮的 web 浏览器给定的输入。
Given below is the CheckBox.java servlet program to handle input given by web browser for checkbox button.
// 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);
}
}
对于上述示例,它会显示以下结果 −
For the above example, it would display following result −
Reading Checkbox Data
Maths Flag : : on
Physics Flag: : null
Chemistry Flag: : on
Reading All Form Parameters
以下是使用 HttpServletRequest 的 getParameterNames() 方法以读取所有可用表单参数的通用示例。此方法返回一个包含按未指定顺序排列的参数名称的枚举。
Following is the generic example which uses getParameterNames() method of HttpServletRequest to read all the available form parameters. This method returns an Enumeration that contains the parameter names in an unspecified order
获得枚举后,我们可以使用 hasMoreElements() 方法来确定何时停止,并使用 nextElement() 方法来获取每个参数名称,从而以标准方式向下遍历枚举。
Once we have an Enumeration, we can loop down the Enumeration in standard way by, using hasMoreElements() method to determine when to stop and using nextElement() method to get each parameter name.
// 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);
}
}
现在,用以下表单尝试上述 Servlet −
Now, try the above servlet with the following form −
<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>
现在,使用上述表单调用 Servlet 将生成以下结果 −
Now calling servlet using the above form would generate the following result −
Reading All Form Parameters
Param Name
Param Value(s)
maths
on
chemistry
on
您可以尝试上述 Servlet 来读取具有其他对象(例如文本框、单选按钮或下拉框等)的任何其他表单的数据。
You can try the above servlet to read any other form’s data having other objects like text box, radio button or drop down box etc.