May 14, 2021 Servlet
4. Use the servlet to read form data
5. An instance of the GET method that uses the URL
6. Use an example of the form's GET method
7. Use an instance of the form's POST method
In many cases, you need to pass some information, from the browser to the Web server, and eventually to the background program. Browsers use two methods to pass this information to the Web server, the GET method and the POST method, respectively.
The GET method requests the page to send encoded user information. B etween the page and encoded information? Character separation, as follows:
http://www.test.com/hello?key1=value1&key2=value2
The GET method is the default way to pass information from the browser to the Web server, and it produces a long string that appears in the browser's address bar. D o not use the GET method if you are passing passwords or other sensitive information to the server. The GET method has a size limit: the request string can only have a maximum of 1024 characters.
This information is QUERY_STRING and can be accessed through QUERY_STRING environment variables, and Servlet uses the doGet() method to handle this type of request.
Another more reliable way to pass information to background programs is the POST method. T he POST method packages information in essentially the same way as the GET method, but the POST method does not treat the information as a URL? T he text string after the character is sent, but the information is treated as a separate message. M essages are sent to the background program as standard output, which you can parse and use. Servlet uses the doPost() method to handle this type of request.
Servlet processes form data, which is automatically resolved in different ways depending on the situation:
Here's a simple URL that will use the GET method to pass two values to the HelloForm program.
http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALIHere's the HelloForm and Servlet .java web browser input. We'll use the getParameter() method to easily access the information passed:
// 导入必需的 java 库
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// 扩展 HttpServlet 类
public class HelloForm extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// 设置响应内容类型
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "使用 GET 方法读取表单数据";
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>");
}
}
Assuming that your environment is set up correctly, compile HelloForm .java, as follows:
$ javac HelloForm.java
If all goes well, the compilation above will result in a HelloForm .class file. Next, you must copy the file to the webapps/ROOT/WEB-INF/classes and create the following entries in the webapps/ROOT-INF/classes file located in the .lt;Tomcat-design-directory/webapps/ROOT/WEB-INF/.xml file:
<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>
Now enter the address bar in your browser to http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI and make sure that the Tomcat server is started before triggering the above command. If all goes well, you'll get the following results:
Use the GET method to read form data
|
Here's a simple example of using an HTML form and a submit button to pass two values. We'll use the same Servlet HelloForm to process the input.
<html>
<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>
Save this HTML to hello .htm file and place it in the directory of the .lt; Tomcat-design-directory/webapps/ROOT directory. When you access http://localhost:8080/Hello.htm, here is the actual output of the form above.
Try entering your first and last name, then click the Submit button to see the output on your machine. Based on the input provided, it produces a similar result to the last instance.
Let's make a small change to the servlet above so that it can handle get and POST methods. The following HelloForm .java Servlet program uses the GET and POST methods to process input given by a web browser.
// 导入必需的 java 库
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// 扩展 HttpServlet 类
public class HelloForm extends HttpServlet {
// 处理 GET 方法请求的方法
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// 设置响应内容类型
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>名字</b>:"
+ request.getParameter("first_name") + "\n" +
" <li><b>姓氏</b>:"
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body></html>");
}
// 处理 POST 方法请求的方法
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Now compile and deploy the servlet above and test it with hello .htm post method, as follows:
<html>
<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>
Here's the actual output of the form above, try entering your first and last name, and then clicking the Submit button to see the output on your machine.
Based on the input provided, it produces a similar result to the last instance.
Use the check box when you need to select more than one option.
Below is an HTML code instance, CheckBox.htm, and a form with two check boxes.
<html>
<body>
<form action="CheckBox" 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>
The result of this code is the following form:
Here's .java CheckBox or Servlet program that handles check box input given by your web browser.
// 导入必需的 java 库
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// 扩展 HttpServlet 类
public class CheckBox extends HttpServlet {
// 处理 GET 方法请求的方法
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// 设置响应内容类型
response.setContentType("text/html");
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><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>数学标识:</b>: "
+ request.getParameter("maths") + "\n" +
" <li><b>物理标识:</b>: "
+ request.getParameter("physics") + "\n" +
" <li><b>化学标识:</b>: "
+ request.getParameter("chemistry") + "\n" +
"</ul>\n" +
"</body></html>");
}
// 处理 POST 方法请求的方法
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
The above example shows the following results:
Read the check box data
|
The following is a generic example of reading all available form parameters using httpServletRequest's getParameterNames() method. The method returns an enumeration that contains parameter names that are not specified in order.
Once we have an enumeration, we can loop the enumeration in a standard way, using the hasMoreElements() method to determine when to stop, and the nextElement() method to get the name of each parameter.
// 导入必需的 java 库
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// 扩展 HttpServlet 类
public class ReadParams extends HttpServlet {
// 处理 GET 方法请求的方法
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// 设置响应内容类型
response.setContentType("text/html");
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><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<td>");
String[] paramValues =
request.getParameterValues(paramName);
// 读取单个值的数据
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<i>No Value</i>");
else
out.println(paramValue);
} else {
// 读取多个值的数据
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>");
}
// 处理 POST 方法请求的方法
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Now try the servlet above from the form below:
<html>
<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>
Calling the servlet now using the form above will produce the following results:
The name of the argument | The value of the argument |
---|---|
maths | on |
chemistry | on |
You can try using the servlet above to read other form data, such as text boxes, turn buttons, or pull-down boxes.