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

วิธีอ่าน Request Header Information ใน JSP


ตัวอย่างต่อไปนี้ใช้เมธอด getHeaderNames() ของ HttpServletRequest เพื่ออ่านข้อมูล HTTP Header เมธอดนี้ส่งคืน Enumeration ที่มีข้อมูล Header ที่เกี่ยวข้องกับคำขอ HTTP ปัจจุบัน

เมื่อเรามี Enumeration แล้ว เราสามารถวนลูปผ่าน Enumeration แบบมาตรฐานได้ เราจะใช้เมธอด 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>Header Name</th>                <th>Header Value(s)</th>             </tr>             <%                Enumeration headerNames = request.getHeaderNames();                while(headerNames.hasMoreElements()) {                   String paramName = (String)headerNames.nextElement();                   out.print("<tr><td>" + paramName + "</td>\n");                   String paramValue = request.getHeader(paramName);                   out.println("<td> " + paramValue + "</td></tr>\n");                }             %>          </table>       </center>    </body> </html>