如何在JSP中读取所有表单参数?
以下是一个通用示例,该示例使用HttpServletRequest的getParameterNames()方法读取所有可用的表单参数。此方法返回一个Enumeration,其中包含未指定顺序的参数名称。
有了枚举后,我们可以使用hasMoreElements()方法确定何时停止并使用nextElement()方法获取每个参数名称,从而以标准方式循环枚举。
<%@ page import = "java.io.*,java.util.*" %>
<html>
<head>
<title>HTTP Header Request Example</title>
</head>
<body>
<center>
<h2>HTTP Header Request Example</h2>
<table width = "100%" border = "1" align = "center">
<tr bgcolor = "#949494">
<th>Param Name</th>
<th>Param Value(s)</th>
</tr>
<%
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n");
String paramValue = request.getHeader(paramName);
out.println("<td> " + paramValue + "</td></tr>\n");
}
%>
</table>
</center>
</body>
</html>以下是Hello.htm的内容-
<html>
<body>
<form action = "main.jsp" 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>现在尝试使用上面的Hello.htm调用JSP;这将基于提供的输入生成如下所示的结果-