Servlet-表单数据
当您需要将一些信息从浏览器传递到Web服务器以及最终传递到后端程序时,您肯定遇到过许多情况。浏览器使用两种方法将此信息传递到Web服务器。这些方法是GET方法和POST方法。
GET方法
GET方法发送附加在页面请求的已编码用户信息。页面和编码信息由符号问号?分隔。如下所示:
http://www.test.com/hello?key1 = value1&key2 = value2
GET方法是将信息从浏览器传递到Web服务器的默认方法,它会生成一个长字符串,该字符串出现在浏览器的Location框中。如果您有密码或其他敏感信息要传递到服务器,请不要使用GET方法。GET方法具有大小限制:请求字符串中只能使用1024个字符。
该信息使用请求参数的标头传递,以及通过请求参数的环境变量进行访问,并且由Servlet使用doGet()方法处理此类请求。
QUERY_STRING(译作“请求参数”)。
POST方法
将信息传递到后端程序的通常更可靠的方法是POST方法。这将使用与GET方法完全相同的方式打包信息,不过相对于在URL里将其作为一个放在问号?后面的文本字符串来发送,它会将其作为独立的信息来发送。此消息以标准输入的形式到达后端程序,您可以对其进行解析并将其用于处理。Servlet使用doPost()方法处理这种类型的请求。
使用Servlet读取表单数据
Servlet根据情况使用以下方法自动处理表单数据解析:
- getParameter():您调用request.getParameter()方法以获取表单参数的值。
- getParameterValues():如果参数出现多次并返回多个值(例如复选框),则调用此方法。
getParameterNames():如果要获取当前请求中所有参数的完整列表,请调用此方法。
使用URL的GET方法示例
这是一个简单的URL,它将使用GET方法将两个值传递给HelloForm程序:
http://localhost:8080/HelloForm?first_name = ZARA&last_name = ALI
下面给出的是HelloForm.java的Servlet程序,用于处理Web浏览器给出的输入。我们将使用getParameter()方法,该方法非常容易访问传递的信息:
// 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 Header
response.setHeader("contentType","text/html;charset=UTF-8");
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String title = "使用URL的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>"
);
}
}
假设您的环境设置正确,请按如下所示编译HelloForm.java:javac HelloForm.java
。
如果报错说字符编码为GBK无法解析的字符的话,可以新建一个系统变量JAVA_TOOL_OPTIONS,变量值为-Dfile.encoding=UTF-8
如果一切顺利,上面的编译将产生HelloForm.class文件。
接下来,把编译后的字节码文件复制到<Tomcat安装目录>/webapps/ROOT/WEB-INF/classes,并在<Tomcat安装目录>/webapps/ROOT/WEB-INF中的web.xml文件中创建以下条目。
<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>
现在,在浏览器的搜索框中键入http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI,并确保在启动浏览器中的上述命令之前已经启动了Tomcat服务器。这将产生以下结果:
使用表单的GET方法示例
这是一个简单的示例,该示例使用HTML FORM和Submit按钮传递两个值。我们将使用相同的Servlet HelloForm来处理此输入。
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body>
<form action = "HelloForm" method = "GET">
姓:<input type = "text" name = "first_name">
<br />
名:<input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
将此HTML保留在Hello.html文件中,并将其放在<Tomcat安装目录>/webapps/ROOT目录中。当您访问http://localhost:8080/Hello.html时,这是上述形式的实际输出。
尝试输入名和姓,然后单击提交按钮以在运行tomcat的本地计算机上查看结果。基于提供的输入,它将生成与以上示例中提到的结果类似的结果。
使用表单的POST方法示例
让我们在上面的servlet中进行少量修改,以便它可以处理GET和POST方法。下面是HelloForm.java Servlet程序,用于处理Web浏览器使用GET或POST方法给出的输入。
// 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 header
response.setHeader("contentType","text/html;charset=UTF-8");
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String title = "使用表单的POST方法示例";
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>"
);
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
现在编译并部署上述Servlet,并使用Hello.html和POST方法对其进行测试,如下所示:
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body>
<form action = "HelloForm" method = "POST">
姓:<input type = "text" name = "first_name">
<br />
名:<input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
这是上面表格的实际输出,请尝试输入名和姓,然后单击提交按钮以在运行tomcat的本地计算机上查看结果。
根据提供的输入,它将生成与以上示例中提到的结果类似的结果。
将复选框数据传递到Servlet程序
当需要选择多个选项时,将使用复选框。
这是带有两个复选框的表单的示例HTML代码CheckBox.html
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<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>
该代码的结果如下表所示
下面提供的CheckBox.java Servlet程序可以处理Web浏览器为复选框按钮提供的输入。编译之后将字节码文件保存在classes目录下并修改好web.xml文件:
// 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 header
response.setHeader("contentType","text/html;charset=UTF-8");
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
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>数学:</b>: "
+ request.getParameter("maths") + "\n" +
" <li><b>物理:</b>: "
+ request.getParameter("physics") + "\n" +
" <li><b>化学:</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);
}
}
对于上面的示例,它将显示以下结果:
读取所有表格参数
以下是使用HttpServletRequest的getParameterNames()方法读取所有可用表单参数的通用示例。此方法返回一个Enumeration,其中包含未指定顺序的参数名称
有了枚举后,我们可以使用hasMoreElements()方法确定何时停止并使用nextElement()方法获取每个参数名称,从而以标准方式循环枚举。
// 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 header
response.setHeader("contentType","text/html;charset=UTF-8");
response.setContentType("text/html");
response.setCharacterEncoding("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><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);
}
}
现在,启动下面的ReadParams.html:
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</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>
现在使用上述形式调用servlet将产生以下结果:
您可以尝试上述servlet读取具有其他对象(例如文本框,单选按钮或下拉框等)的任何其他表单的数据。
上一篇: Servlet-示例
下一篇: Servlet-客户端请求