如何读取 JSP 中的所有表单参数?
以下是使用**getParameterNames()**方法HttpServletRequest来读取所有可用表单参数的一个通用示例。此方法返回一个包含参数名的枚举,其顺序不确定。
有了枚举之后,我们可以使用**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>
"); String paramValue = request.getHeader(paramName); out.println("<td> " + paramValue + "</td></tr>
"); } %> </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;这将生成如下面的结果 -
读取所有表单参数
参数名 | 参数值 |
---|---|
数学 | 开启 |
化学 | 开启 |
广告