Servlet顯示所有頭信息

ServletRequest接口的getHeaderNames()方法返回一個包含所有頭名稱的Enumeration對象。ServletRequest接口的getHeader()方法返回給定頭名稱的頭值。 在這個例子中,我們在servlet頁面中顯示一個請求的所有頭信息。

getHeaderNames()方法的語法

public Enumeration getHeaderNames()

getHeader()方法的語法

public String getHeader(String headerName)

在servlet中顯示所有頭信息的示例

在本示例中,我們調用ServletRequest接口的getHeaderNames()方法,該方法返回包含所有頭名稱的Enumeration對象。通過調用getHeader()方法來獲取和顯示所有的報頭值。下面來看一個例子:

打開Eclipse,創建一個動態Web項目:ShowHeaders,並在com.yiibai包下創建一個名稱爲:HeaderServlet.java的Servlet類以及在WebContent目錄下創建一個HTML文件:index.html,如下所示 -

Servlet顯示所有頭信息

完整的代碼實現如下所示 -

文件:index.html -

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ShowHeaders Servlet</title>
</head>
<body>
    <div style="text-align: center;">
        請<a href="/ShowHeaders/headers?key1=name">點擊這裏</a>查看所有報頭信息
    </div>
</body>
</html>

文件:HeaderServlet.java -

package com.yiibai;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HeaderServlet
 */
public class HeaderServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        // out.println("HTTP headers sent by your client:<br>");

        Enumeration enums = request.getHeaderNames();
        while (enums.hasMoreElements()) {
            String headerName = (String) enums.nextElement();
            String headerValue = request.getHeader(headerName);
            out.print("<b>" + headerName + "</b>: ");
            out.println(headerValue + "<br/>");
        }
    }

}

文件:web.xml -

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
    <display-name>ShowHeaders-HeaderServlet</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>HeaderServlet</servlet-name>
        <servlet-class>com.yiibai.HeaderServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>HeaderServlet</servlet-name>
        <url-pattern>/headers</url-pattern>
    </servlet-mapping>
</web-app>

執行結果如下所示 -

Servlet顯示所有頭信息