返回顶部

收藏

在Servlet中获得所有http请求头

更多
package cn.outofmemory.snippets.enterprise;

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

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetAllRequestHeadersInServlet extends HttpServlet {

    private static final long serialVersionUID = -2128122335811219481L;

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        handleRequest(req, res);
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
        handleRequest(req, res);
    }

    public void handleRequest(HttpServletRequest req, HttpServletResponse res) throws IOException {

        PrintWriter out = res.getWriter();
        res.setContentType("text/plain");

        Enumeration<String> headerNames = req.getHeaderNames();

        while (headerNames.hasMoreElements()) {

            String headerName = headerNames.nextElement();
            out.write(headerName);
            out.write("\n");

            Enumeration<String> headers = req.getHeaders(headerName);
            while (headers.hasMoreElements()) {
                String headerValue = headers.nextElement();
                out.write("\t" + headerValue);
                out.write("\n");
            }

        }

        out.close();

    }

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  version="2.5">

    <display-name>JCG Snippets Web Project</display-name>

    <servlet>
        <servlet-name>JCG Snippets Application</servlet-name>
        <servlet-class>cn.outofmemory.snippets.enterprise.GetAllRequestHeadersInServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>JCG Snippets Application</servlet-name>
        <url-pattern>/jcgservlet</url-pattern>
    </servlet-mapping>

</web-app>

URL:

http://myhost:8080/jcgsnippets/jcgservlet

输出:

host
    myhost:8080
user-agent
    Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0
accept
    text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

......

标签:java,Servlet,HTTP

收藏

1人收藏

支持

0

反对

1

评论

  • 你这么整谁看得见................

    回复   |   紫辰 发表于 2015-06-06 12:50:06

发表评论