Servlet 教程 之 Servlet 表单数据 8
Servlet 表单数据
读取所有的表单参数
以下是通用的实例,使用 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\n");
}/**
- @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>
数学
物理
化学
设置相应的 web.xml:
<?xml version="1.0" encoding="UTF-8"?>
ReadParams
com.baidu.test.ReadParams
ReadParams
/TomcatTest/ReadParams