HttpServletRequest对象——获取请求头

方法

  • getHeaderNames() //获取所有的请求头
  • getHeader(String s) //根据请求头的名字获取请求头的值

实例

package net.test.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@WebServlet(name="helloServlet",urlPatterns="/header")  //1、配置servlet
public class HelloServlet extends HttpServlet {  //2、继承HttpServlet

    //3、重写doPost方法
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }

    //3、重写doGet方法
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Enumeration headerNames = req.getHeaderNames();
        while(headerNames.hasMoreElements()){
            String element = headerNames.nextElement();
            System.out.println(element+":"+req.getHeader(element));
        }
    }
}

在浏览器上运行:
HttpServletRequest对象——获取请求头_第1张图片
运行结果:
HttpServletRequest对象——获取请求头_第2张图片

你可能感兴趣的:(javaweb)