Servlet如何输出所有头信息呢?
下文讲述使用Servlet输出头信息的方法分享,如下所示:
输出客户端所有头信息的方法分享
实现思路: 使用ServletRequest对象中的getHeaderNames()方法 即可返回一个包含所有头名称的Enumeration对象
getHeaderNames()方法的语法
getHeaderNames()方法的语法 public Enumeration getHeaderNames() getHeader()方法的语法 public String getHeader(String headerName)例:
输出客户端所有头信息的方法分享
index.html:调用Servlet对象 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>ShowHeaders Servlet</title> </head> <body> <div style="text-align: center;"> 请<a href="/servlet/HelloServlet?info=other">点击这里</a>查看所有报头信息 </div> </body> </html> HelloServlet.java package com.java265; 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; public class HelloServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); 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>HelloServlet</servlet-name> <servlet-class>com.java265.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/HelloServlet</url-pattern> </servlet-mapping> </web-app>
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。