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

วิธีอ่านข้อมูลฟอร์มใน JSP

JSP จัดการข้อมูลฟอร์มอัตโนมัติ ผ่าน request object มีเมธอดหลัก 4 ตัว:

เมธอดใช้เมื่อไหร่คืนค่า
getParameter(name)อ่านพารามิเตอร์เดี่ยว (text, hidden, select, radio)String หรือ null
getParameterValues(name)อ่านพารามิเตอร์หลายค่า (checkbox กลุ่ม, multi-select)String[]
getParameterNames()ดึงชื่อพารามิเตอร์ทั้งหมดEnumeration<String>
getInputStream()อ่าน binary data (file upload)ServletInputStream

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

<%@ page import="java.io.*,java.util.*" %>
<html>
<head><title>อ่านพารามิเตอร์ทั้งหมด</title></head>
<body>
    <center>
        <h2>พารามิเตอร์ที่ได้รับ</h2>
        <table border="1">
            <tr><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>

ผลลัพธ์ตัวอย่าง

Param NameParam Value(s)
mathson
chemistryon

หมายเหตุ: physics ไม่ปรากฏเพราะไม่ได้ติ๊ก (checkbox ที่ไม่ติ๊กไม่ส่งค่า)