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

วิธีอ่าน HTTP Header ด้วย 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>

นำโค้ดข้างต้นใส่ใน main.jsp และลองเข้าถึง

HTTP Header Request Example

Header Name Header Value(s)
accept */*
accept-language en-us
user-agent Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; InfoPath.2; MS-RTC LM 8)
accept-encoding gzip, deflate
host localhost:8080
connection Keep-Alive
cache-control no-cache