如何讀取 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;這將生成如下面的結果 -

讀取所有表單引數

引數名引數值
數學開啟
化學開啟

更新於: 2019-07-30

1K+ 閱讀量

啟動你的 事業

透過完成課程獲得認證

開始
廣告