从 01 开始 从 01 开始
首页
  • 📚 计算机基础

    • 计算机简史
    • 数字电路
    • 计算机组成原理
    • 操作系统
    • Linux
    • 计算机网络
    • 数据库
    • 编程工具
    • 装机
  • 🎨 前端

    • Node
  • JavaSE
  • Java 高级
  • JavaEE

    • 构建、依赖管理
    • Ant
    • Maven
    • 日志框架
    • Junit
    • JDBC
    • XML-JSON
  • JavaWeb

    • 服务器软件
    • 环境管理和配置管理-科普篇
    • Servlet
  • Spring

    • Spring基础
  • 主流框架

    • Redis
    • Mybatis
    • Lucene
    • Elasticsearch
    • RabbitMQ
    • MyCat
    • Lombok
  • SpringMVC

    • SpringMVC 基础
  • SpringBoot

    • SpringBoot 基础
  • Windows 使用技巧
  • 手机相关技巧
  • 最全面的输入法教程
  • 最全面的浏览器教程
  • Office
  • 图片类工具
  • 效率类工具
  • 最全面的 RSS 教程
  • 码字工具
  • 各大平台
  • 校招
  • 五险一金
  • 职场规划
  • 关于离职
  • 杂谈
  • 自媒体
  • 📖 读书

    • 读书工具
    • 走进科学
  • 🌍 英语

    • 从零开始学英语
    • 英语兔的相关视频
    • Larry 想做技术大佬的相关视频
  • 🏛️ 政治

    • 新闻合订本
    • 反腐
    • GFW
    • 404 内容
    • 审查与自我审查
    • 互联网
    • 战争
    • 读书笔记
  • 💰 经济

    • 关于税
    • 理财
  • 💪 健身

    • 睡眠
    • 皮肤
    • 口腔健康
    • 学会呼吸
    • 健身日志
  • 🏠 其他

    • 驾驶技能
    • 租房与买房
    • 厨艺
  • 电影

    • 电影推荐
  • 电视剧
  • 漫画

    • 漫画软件
    • 漫画推荐
  • 游戏

    • Steam
    • 三国杀
    • 求生之路
  • 小说
  • 关于本站
  • 关于博主
  • 打赏
  • 网站动态
  • 友人帐
  • 从零开始搭建博客
  • 搭建邮件服务器
  • 本站分享
  • 🌈 生活

    • 2022
    • 2023
    • 2024
    • 2025
  • 📇 文章索引

    • 文章分类
    • 文章归档

晓林

程序猿,自由职业者,博主,英语爱好者,健身达人
首页
  • 📚 计算机基础

    • 计算机简史
    • 数字电路
    • 计算机组成原理
    • 操作系统
    • Linux
    • 计算机网络
    • 数据库
    • 编程工具
    • 装机
  • 🎨 前端

    • Node
  • JavaSE
  • Java 高级
  • JavaEE

    • 构建、依赖管理
    • Ant
    • Maven
    • 日志框架
    • Junit
    • JDBC
    • XML-JSON
  • JavaWeb

    • 服务器软件
    • 环境管理和配置管理-科普篇
    • Servlet
  • Spring

    • Spring基础
  • 主流框架

    • Redis
    • Mybatis
    • Lucene
    • Elasticsearch
    • RabbitMQ
    • MyCat
    • Lombok
  • SpringMVC

    • SpringMVC 基础
  • SpringBoot

    • SpringBoot 基础
  • Windows 使用技巧
  • 手机相关技巧
  • 最全面的输入法教程
  • 最全面的浏览器教程
  • Office
  • 图片类工具
  • 效率类工具
  • 最全面的 RSS 教程
  • 码字工具
  • 各大平台
  • 校招
  • 五险一金
  • 职场规划
  • 关于离职
  • 杂谈
  • 自媒体
  • 📖 读书

    • 读书工具
    • 走进科学
  • 🌍 英语

    • 从零开始学英语
    • 英语兔的相关视频
    • Larry 想做技术大佬的相关视频
  • 🏛️ 政治

    • 新闻合订本
    • 反腐
    • GFW
    • 404 内容
    • 审查与自我审查
    • 互联网
    • 战争
    • 读书笔记
  • 💰 经济

    • 关于税
    • 理财
  • 💪 健身

    • 睡眠
    • 皮肤
    • 口腔健康
    • 学会呼吸
    • 健身日志
  • 🏠 其他

    • 驾驶技能
    • 租房与买房
    • 厨艺
  • 电影

    • 电影推荐
  • 电视剧
  • 漫画

    • 漫画软件
    • 漫画推荐
  • 游戏

    • Steam
    • 三国杀
    • 求生之路
  • 小说
  • 关于本站
  • 关于博主
  • 打赏
  • 网站动态
  • 友人帐
  • 从零开始搭建博客
  • 搭建邮件服务器
  • 本站分享
  • 🌈 生活

    • 2022
    • 2023
    • 2024
    • 2025
  • 📇 文章索引

    • 文章分类
    • 文章归档
  • JavaSE

  • JavaSenior

  • JavaEE

  • JavaWeb

    • 服务器软件

    • 环境管理和配置管理-科普篇
    • Servlet 入门

      • 什么是 Servlet
      • Servlet 入门案例
      • Servlet 生命周期
      • Servlet 中的注解
      • Tomcat 集成 IDEA
      • Servlet 体系结构
      • HTTP 协议基础
      • 深入 request 和 response 对象
      • request 对象基本使用
        • 获取请求行数据
        • 获取请求头数据
        • 获取请求体数据
      • request 其他功能
      • Servlet 实现登录功能
      • HTTP 协议基础-响应
      • Response 对象基本使用
      • response 对象之重定向
      • response 输出字符到浏览器
      • response 输出字节数据
      • 验证码案例
      • ServletContext
      • 文件下载案例
      • Cookie 笔记
      • Cookie 的更多细节
      • Cookie 实践:记住上次访问时间
      • JSP 入门
      • JSP 的内置对象和案例
      • IDEA 与 JavaWeb 的小技巧
      • Session 笔记
      • 验证码案例
      • JSP 深入学习
      • MVC 开发模式
      • EL 表达式和 JSTL 标签
      • JSTL 标签库
      • 案例:列表的增删改查
      • Filter 学习
      • Filter 案例
      • Listener 学习
      • Java 中的 Ajax
      • Java 中的 JSON
  • Spring

  • 主流框架

  • SpringMVC

  • SpringBoot

  • Java
  • JavaWeb
  • Servlet 入门
2023-04-17
目录

request 对象基本使用

# 31.request 对象基本使用

来演示下 request 对象的使用:获取请求数据和其他功能,本文就来讲解下获取请求数据的方法。

根据我们学习的 HTTP 协议,请求消息数据主要分为请求行、请求头和请求头。我们来看看如何获取这些数据

# 获取请求行数据

请求行的格式:请求方式 请求 url 请求协议/版本

例如 GET /hello/httpDemo1 HTTP/1.1 ‍ 获取请求行数据的方法:

  • 获取请求方式 :String getMethod(),本例中请求方式是 GET

  • 获取虚拟目录(重要):String getContextPath(),本例中虚拟目录是 /hello

  • 获取 Servlet 路径:String getServletPath(),本例中 Servlet 路径是 httpDemo1

  • 获取 get 方式请求参数:String getQueryString(),会用&分隔

  • 获取请求 URI(重要):

    • String getRequestURI(),获取统一资源标识符,例如 /hello/httpDemo1
    • StringBuffer getRequestURL(),获取统一资源定位符,例如 http://localhost:8080/hello/httpDemo1
  • 获取协议及版本:String getProtocol(),该方法继承自父接口 Interface ServletRequest

  • 获取客户机的 IP 地址:String getRemoteAddr(),继承自父接口 Interface ServletRequest ‍ 我们新建一个类来演示下上述方法:

package com.peterjxl.request;

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;

/**
 * 演示Request对象获取请求行数据
 */

@WebServlet("/requestDemo1")
public class RequestDemo1 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getMethod();    //1. 获取请求方式:get
        String contextPath = req.getContextPath();  //2。获取虚拟目录,/hello
        String servletPath = req.getServletPath();  //3.获取Servlet路径,/requestDemo1
        String queryString = req.getQueryString();  //4.获取get方式请求参数
        String requestURI  = req.getRequestURI();   //5.获取请求URI:/hello/requestDemo1
        StringBuffer requestURL = req.getRequestURL();  //5. 获取请求URL:
        String protocol = req.getProtocol();    //6.获取协议版本 HTTP/1.1
        String remoteAddr = req.getRemoteAddr();    //7.获取客户的IP地址

        System.out.println("method: " + method);
        System.out.println("contextPath: " + contextPath);
        System.out.println("servletPath: " + servletPath);
        System.out.println("queryString: " + queryString);
        System.out.println("requestURI: " + requestURI);
        System.out.println("requestURL: " + requestURL);
        System.out.println("protocol: " + protocol);
        System.out.println("remoteAddr: " + remoteAddr);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

‍ 重启 Tomcat,然后在浏览器里输入

http://localhost:8080/hello/requestDemo1?username=peterjxl&age=3
1

‍ IDEA 里的控制台输出:

method: GET
contextPath: /hello
servletPath: /requestDemo1
queryString: username=peterjxl&age=3
requestURI: /hello/requestDemo1
requestURL: http://localhost:8080/hello/requestDemo1
protocol: HTTP/1.1
remoteAddr: 0:0:0:0:0:0:0:1
1
2
3
4
5
6
7
8

# 获取请求头数据

主要有两个方法获取:

  • String getHeader(String name) ** ** : 通过 请求头的名称 获取 请求头的值,不区分大小写。获取 refer 属性的时候,如果是直接访问该路径,则获取的对象是 null,因为不是从其他地址跳转到该路径的。
  • Enumeration<String> getHeaderNames(): 获取所有的请求头名称,返回一个迭代器

第一个方法使用频率较高,第二个方法知道即可。 ‍ 写个类演示下:

package com.peterjxl.request;

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;

/**
 * 演示Request对象获取请求头数据
 */

@WebServlet("/requestDemo2")
public class RequestDemo2 extends HttpServlet {
    //演示获取请求头数据
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取某个请求头信息
        String agent = req.getHeader("user-agent");
        System.out.println("agent: " + agent);

        // 获取所有请求头名称
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()){
            String name = headerNames.nextElement();
            String value = req.getHeader(name); //根据名称获取请求头的值
            System.out.println(name + " : " + value);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

访问 http://localhost: 8080/hello/requestDemo2,观察输出:

agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36

host : localhost:8080
connection : keep-alive
cache-control : max-age=0
sec-ch-ua : "Google Chrome";v="111", "Not(A:Brand";v="8", "Chromium";v="111"
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/111.0.0.0 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.7
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

‍ 获取请求头信息有什么用呢?例如判断浏览器版本:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //演示获取请求头数据:user-agent

    String agent = request.getHeader("user-agent");
    //判断agent的浏览器版本
    if(agent.contains("Chrome")){
        //谷歌
        System.out.println("谷歌来了...");
    }else if(agent.con tains("Firefox")){
        //火狐
        System.out.println("火狐来了...");
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

‍ 还可以通过获取 refer 信息,来判断是否盗链。 ‍

# 获取请求体数据

请求体:只有 POST 请求方式,才有请求体,在请求体中封装了 POST 请求的请求参数 ‍ request 对象将请求体数据封装成流。因此想要获取请求头,得这样做:

  1. 获取流对象

    • BufferedReader getReader():获取字符输入流,只能操作字符数据,该方法继承自 ServletRequest。使用完后不用关闭,request 会自动关闭的。
    • ServletInputStream getInputStream():获取字节输入流,可以操作所有类型数据(但不方便处理字符),例如文件,图片等,继承了 InputStream,在后续文件上传知识点后讲解
  2. 再从流对象中拿数据 ‍ 新建一个类来演示:

package com.peterjxl.request;

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

/**
 * 演示Request对象获取请求体数据
 */

@WebServlet("/requestDemo3")
public class RequestDemo3 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader reader = req.getReader();
        String line;
        while ( null !=  (line = reader.readLine())){
            System.out.println(line);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

‍ 然后新建一个 regist.html 文件来发送 post 请求:

<!DOCTYPE html>
<html lang="ch">
    <head>
        <meta charset="UTF-8">
        <title>注册页面</title>
    </head>

    <body>
        <form action="/hello/requestDemo3" method="post">
            <input type="text" placeholder="请输入用户名" name="username"><br>
            <input type="text" placeholder="请输入密码" name="password"><br>
            <input type="submit" value="注册">
        </form>
    </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

‍ 重启 Tomcat,访问 http://localhost: 8080/hello/regist.html,并输入用户名和密码,点击注册

‍

可以看到控制台输出:

username=peterjxl&password=123456
1
上次更新: 2025/6/3 09:31:54
深入 request 和 response 对象
request 其他功能

← 深入 request 和 response 对象 request 其他功能→

最近更新
01
新闻合订本 2025-10
10-31
02
2025 年 10 月记
10-30
03
用 AI 批量优化思源笔记排版
10-15
更多文章>
Theme by Vdoing | Copyright © 2022-2025 | 粤 ICP 备 2022067627 号 -1 | 粤公网安备 44011302003646 号 | 点击查看十年之约
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式