从01开始 从01开始
首页
  • 计算机科学导论
  • 数字电路
  • 计算机组成原理

    • 计算机组成原理-北大网课
  • 操作系统
  • Linux
  • Docker
  • 计算机网络
  • 计算机常识
  • Git
  • JavaSE
  • Java高级
  • JavaEE

    • Ant
    • Maven
    • Log4j
    • Junit
    • JDBC
    • XML-JSON
  • JavaWeb

    • 服务器软件
    • Servlet
  • Spring
  • 主流框架

    • Redis
    • Mybatis
    • Lucene
    • Elasticsearch
    • RabbitMQ
    • MyCat
    • Lombok
  • SpringMVC
  • SpringBoot
  • 学习网课的心得
  • 输入法
  • 节假日TodoList
  • 其他
  • 关于本站
  • 网站日记
  • 友人帐
  • 如何搭建一个博客
GitHub (opens new window)

peterjxl

人生如逆旅,我亦是行人
首页
  • 计算机科学导论
  • 数字电路
  • 计算机组成原理

    • 计算机组成原理-北大网课
  • 操作系统
  • Linux
  • Docker
  • 计算机网络
  • 计算机常识
  • Git
  • JavaSE
  • Java高级
  • JavaEE

    • Ant
    • Maven
    • Log4j
    • Junit
    • JDBC
    • XML-JSON
  • JavaWeb

    • 服务器软件
    • Servlet
  • Spring
  • 主流框架

    • Redis
    • Mybatis
    • Lucene
    • Elasticsearch
    • RabbitMQ
    • MyCat
    • Lombok
  • SpringMVC
  • SpringBoot
  • 学习网课的心得
  • 输入法
  • 节假日TodoList
  • 其他
  • 关于本站
  • 网站日记
  • 友人帐
  • 如何搭建一个博客
GitHub (opens new window)
  • 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
      • Servlet
    • JavaWeb
  • Spring

  • 主流框架

  • SpringMVC

  • SpringBoot

  • Java并发

  • Java源码

  • JVM

  • 韩顺平

  • Java
  • 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

‍

‍

在GitHub上编辑此页 (opens new window)
上次更新: 2023/4/21 16:56:30
深入request和response对象
request其他功能

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

Theme by Vdoing | Copyright © 2022-2023 粤ICP备2022067627号-1 粤公网安备 44011302003646号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式