Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

วิธีอ่านพารามิเตอร์ฟอร์มทั้งหมดใน JSP

ใช้ request.getParameterNames() ดึงชื่อพารามิเตอร์ทั้งหมด (Enumeration) แล้ววนลูปอ่านค่า

ตัวอย่าง JSP อ่านพารามิเตอร์ทั้งหมด

<%@ page import="java.io.*,java.util.*" %>
<html>
<head><title>อ่านพารามิเตอร์ทั้งหมด</title></head>
<body>
    <center>
        <h2>พารามิเตอร์ฟอร์มทั้งหมด</h2>
        <table border="1" width="100%">
            <tr bgcolor="#949494">
                <th>Param Name</th><th>Param Value(s)</th>
            </tr>
            <%
                Enumeration<String> paramNames = request.getParameterNames();
                while (paramNames.hasMoreElements()) {
                    String paramName = paramNames.nextElement();
                    String[] values = request.getParameterValues(paramName);
                    out.print("<tr><td>" + paramName + "</td><td>");
                    if (values != null) {
                        for (int i = 0; i < values.length; i++) {
                            if (i > 0) out.print(", ");
                            out.print(values[i]);
                        }
                    }
                    out.println("</td></tr>");
                }
            %>
        </table>
    </center>
</body>
</html>

ไฟล์ทดสอบ (Hello.htm)

<html>
<body>
    <form action="main.jsp" method="POST">
        <input type="checkbox" name="maths" checked="checked" /> Maths
        <input type="checkbox" name="physics" /> Physics
        <input type="checkbox" name="chemistry" checked="checked" /> Chemistry
        <input type="submit" value="Select Subject" />
    </form>
</body>
</html>

ผลลัพธ์ตัวอย่าง (ติ๊ก Maths และ Chemistry)

Param NameParam Value(s)
mathson
chemistryon

จุดสำคัญ

  • getParameterNames() คืน Enumeration<String> ใช้ hasMoreElements() และ nextElement() วนลูป
  • ใช้ getParameterValues() แทน getParameter() เพื่อรองรับ multi-value (checkbox, multi-select)
  • Checkbox ที่ไม่ติ๊กจะไม่ส่งค่า จึงไม่ปรากฏในรายการ
  • วิธีนี้เหมาะสำหรับ debug, logging, หรือ generic form handler