Java Servlet - 获取请求头

Writing Service Methods

The service provided by a servlet is implemented in the service method of a GenericServlet, in the doMethod methods (where Method can take the value Get, Delete, Options, Post, Put, or Trace) of an HttpServlet object, or in any other protocol-specific methods defined by a class that implements the Servlet interface. The term service method is used for any method in a servlet class that provides a service to a client.

The general pattern for a service method is to extract information from the request, access external resources, and then populate the response, based on that information. For HTTP servlets, the correct procedure for populating the response is to do the following:

  1. Retrieve an output stream from the response.
  2. Fill in the response headers.
  3. Write any body content to the output stream.

Response headers must always be set before the response has been committed. The web container will ignore any attempt to set or add headers after the response has been committed. The next two sections describe how to get information from requests and generate responses.

实践

环境

操作系统:

Windows 10 x64

集成开发环境:

Eclipse IDE for Enterprise Java and Web Developers (includes Incubating components)

Version: 2021-09 (4.21.0)

Build id: 20210910-1417

服务器:

apache-tomcat-9.0.55

客户端:

谷歌浏览器:版本 96.0.4664.93(正式版本) (64 位)

火狐浏览器:95.0.2 (64 位)

新建项目

新建 Dynamic Web Project

在这里插入图片描述

获取请求头

新建一个 HeaderServlet 类,继承自 HttpServlet

  • 使用 @WebServlet 注解,指定 urlPatterns 属性;

  • 重写 doGet 方法,用于处理 GET 请求;使用 getHeadergetHeaders 方法都可以获取请求头,但两者有点小区别,详见方法上的注释。

package com.mk.servlet;

import java.io.IOException;
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;

@WebServlet(urlPatterns = "/header")
public class HeaderServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Enumeration<String> headerNames = request.getHeaderNames();
        
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            
            Enumeration<String> headers = request.getHeaders(name);
            while (headers.hasMoreElements()) {
                String value = headers.nextElement();
                
                System.out.println(name + ": " + value);
            }
        }
    }
}

测试

使用火狐浏览器测试

启动服务器,启动火狐浏览器,打开开发者工具,访问 http://localhost:8080/hello-servlet/header,请求成功之后,可以在开发者工具网络选项卡中,可以看到我们发起的请求信息:

在这里插入图片描述

在 Eclipse IDE 的控制台中,输出:

host: localhost:8080
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
accept-language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
accept-encoding: gzip, deflate
connection: keep-alive
upgrade-insecure-requests: 1
sec-fetch-dest: document
sec-fetch-mode: navigate
sec-fetch-site: none
sec-fetch-user: ?1

使用谷歌浏览器测试

启动谷歌浏览器,打开开发者工具,访问 http://localhost:8080/hello-servlet/header,请求成功之后,可以在开发者工具网络选项卡中,可以看到我们发起的请求信息:

在这里插入图片描述

在 Eclipse IDE 的控制台中,输出:

host: localhost:8080
connection: keep-alive
cache-control: max-age=0
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
sec-fetch-site: none
sec-fetch-mode: navigate
sec-fetch-user: ?1
sec-fetch-dest: document
accept-encoding: gzip, deflate, br
accept-language: zh-CN,zh;q=0.9

参考

Java Servlet Technology - Writing Service Methods

Web 开发技术 > HTTP > HTTP Headers

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值