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

Cách đọc HTTP header bằng JSP

Ví dụ sau sử dụng phương thức getHeaderNames() của HttpServletRequest để đọc thông tin HTTP header. Phương thức này trả về một Enumeration chứa thông tin header liên quan đến HTTP request hiện tại.

Khi đã có Enumeration, chúng ta có thể lặp qua nó theo cách tiêu chuẩn. Sử dụng phương thức hasMoreElements() để xác định khi dừng và nextElement() để lấy tên của từng 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>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>

Đặt code trên vào main.jsp và truy cập.

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