Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình

Cách đọc tất cả tham số form trong JSP

Ví dụ chung dùng getParameterNames() của HttpServletRequest đọc tất cả tham số form. Phương thức trả về Enumeration chứa tên tham số theo thứ tự không xác định.

Dùng hasMoreElements() để biết khi dừng, nextElement() lấy từng tên tham số.

<%@ 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.getParameter(paramName);
            out.println("<td> " + paramValue + "</td></tr>\n");
          }
        %>
      </table>
    </center>
  </body>
</html>

Lưu ý: Code gốc dùng request.getHeader(paramName) – sai, phải dùng request.getParameter(paramName).

File 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>

Gọi JSP qua Hello.htm cho kết quả (dựa trên input):

Param NameParam Value(s)
mathson
chemistryon