SpringBoot系列教程web篇之Post请求参数解析姿势汇总

简介: 作为一个常年提供各种Http接口的后端而言,如何获取请求参数可以说是一项基本技能了,本篇为《190824-SpringBoot系列教程web篇之Get请求参数解析姿势汇总》之后的第二篇,对于POST请求方式下,又可以怎样获取请求参数呢

作为一个常年提供各种Http接口的后端而言,如何获取请求参数可以说是一项基本技能了,本篇为《190824-SpringBoot系列教程web篇之Get请求参数解析姿势汇总》之后的第二篇,对于POST请求方式下,又可以怎样获取请求参数呢


本篇主要内容包括以下几种姿势


  • @RequestBody  json格式
  • RequestEntity
  • MultipartFile 文件上传


I. 环境搭建



首先得搭建一个web应用才有可能继续后续的测试,借助SpringBoot搭建一个web应用属于比较简单的活;


创建一个maven项目,pom文件如下

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.7</version>
    <relativePath/> <!-- lookup parent from update -->
</parent>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
    <java.version>1.8</java.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>
<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </pluginManagement>
</build>
<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>
复制代码


添加项目启动类Application.cass

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}
复制代码


在演示请求参数的解析实例中,我们使用终端的curl命令来发起http请求(主要原因是截图上传太麻烦,还是终端的文本输出比较方便;缺点是不太直观)


II. POST请求参数解析



接下来我们正式进入参数解析的妖娆姿势篇,会介绍一下常见的一些case(并不能说包含了所有的使用case)


下面所有的方法都放在 ParamPostRest 这个Controller中


@RestController
@RequestMapping(path = "post")
public class ParamPostRest {
}
复制代码

在正式介绍之前,强烈推荐看一下《190824-SpringBoot系列教程web篇之Get请求参数解析姿势汇总》, 因为get传参的姿势,在post参数解析中同样适用,下面的内容并不会再次详细介绍


1. HttpServletRequest


首先看一下最基本的使用case,和get请求里的case一样,我们先开一个接口


@PostMapping(path = "req")
public String requestParam(HttpServletRequest req) {
    return JSONObject.toJSONString(req.getParameterMap());
}
复制代码


我们测试下两种post请求下,会出现怎样的结果


# 常规的表单提交方式
# content-type: application/x-www-form-urlencoded
➜  ~ curl 'http://127.0.0.1:8080/post/req' -X POST -d 'name=yihui&age=18'
{"name":["yihui"],"age":["18"]}% 
# json传提交
➜  ~ curl 'http://127.0.0.1:8080/post/req' -X POST -H 'content-type:application/json;charset:UTF-8' -d '{"name": "yihui", "age": 20}'
{}%
复制代码


从上面的case中可以知道,通过传统的表达方式提交的数据时,获取参数和get获取参数使用姿势一样;然而当然传入的是json串格式的数据时,直接通过javax.servlet.ServletRequest#getParameter获取不到对应的参数


我们通过debug,来看一下在传json串数据的时候,如果我们要获取数据,可以怎么做


image.png


上面截图演示了我们从请求的InputStream中获取post参数;所以再实际使用的时候需要注意,流中的数据只能读一次,读完了就没了; 这个和我们使用GET传参是有很大的差别的


注意:如果您有一个打印请求参数日志的切面,在获取post传的参数时需要注意,是不是把流的数据读了,导致业务中无法获取到正确的数据!!!


2. RequestBody


上面说到传json串数据时,后端直接通过HttpServletRequest获取数据不太方便,那么有更优雅的使用姿势么?下面我们看一下@RequestBody注解的使用


@Data
public class BaseReqDO implements Serializable {
    private static final long serialVersionUID = 8706843673978981262L;
    private String name;
    private Integer age;
    private List<Integer> uIds;
}
@PostMapping(path = "body")
public String bodyParam(@RequestBody BaseReqDO req) {
    return req == null ? "null" : req.toString();
}
复制代码


只需要在参数中添加@RequestBody注解即可,然后这个接口就支持json串的POST提交了


# json串数据提交
➜  ~ curl 'http://127.0.0.1:8080/post/body' -X POST -H 'content-type:application/json;charset:UTF-8' -d '{"name": "yihui", "age": 20}'
BaseReqDO(name=yihui, age=20, uIds=null)%
# 表单数据提交
➜  ~ curl 'http://127.0.0.1:8080/post/body' -X POST -d 'name=yihui&age=20'
{"timestamp":1566987651551,"status":415,"error":"Unsupported Media Type","message":"Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported","path":"/post/body"}%
复制代码


说明:使用@RequestBody注解之后,可解析提交的json串;但不再支持表单提交参数方式(application/x-www-form-urlencoded)


3. RequestEntity


使用RequestEntity来解析参数,可能并不太常见,它用来解析json串提交的参数也比较合适,使用姿势也比较简单


@PostMapping(path = "entity")
public String entityParam(RequestEntity requestEntity) {
    return Objects.requireNonNull(requestEntity.getBody()).toString();
}
复制代码


使用case如下


# json串数据提交
➜  ~ curl 'http://127.0.0.1:8080/post/entity' -X POST -H 'content-type:application/json;charset:UTF-8' -d '{"name": "yihui", "age": 20}'
{name=yihui, age=20}%
# 表单数据提交不行
➜  ~ curl 'http://127.0.0.1:8080/post/entity' -X POST -d 'name=yihui&age=19'
{"timestamp":1566988137298,"status":415,"error":"Unsupported Media Type","message":"Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported","path":"/post/entity"}%
复制代码


4. MultipartFile 文件上传


文件上传也是一个比较常见的,支持起来也比较简单,有两种方式,一个是使用MultipartHttpServletRequest参数来获取上传的文件;一个是借助 @RequestParam注解


private String getMsg(MultipartFile file) {
    String ans = null;
    try {
        ans = file.getName() + " = " + new String(file.getBytes(), "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
        return e.getMessage();
    }
    System.out.println(ans);
    return ans;
}
/**
 * 文件上传
 *
 * curl 'http://127.0.0.1:8080/post/file' -X POST -F 'file=@hello.txt'
 *
 * @param file
 * @return
 */
@PostMapping(path = "file")
public String fileParam(@RequestParam("file") MultipartFile file) {
    return getMsg(file);
}
@PostMapping(path = "file2")
public String fileParam2(MultipartHttpServletRequest request) {
    MultipartFile file = request.getFile("file");
    return getMsg(file);
}
复制代码


测试case如下

# 创建一个文本文件
➜  ~ vim hello.txt
hello, this is yhh's spring test!
# 使用curl -F 实现文件上传,注意使用姿势
➜  ~ curl 'http://127.0.0.1:8080/post/file' -F 'file=@hello.txt'
file = hello, this is yhh's spring test!
➜  ~ curl 'http://127.0.0.1:8080/post/file2' -F 'file=@hello.txt'
file = hello, this is yhh's spring test!


相关文章
|
7月前
|
人工智能 Java 开发者
【Spring】原理解析:Spring Boot 自动配置
Spring Boot通过“约定优于配置”的设计理念,自动检测项目依赖并根据这些依赖自动装配相应的Bean,从而解放开发者从繁琐的配置工作中解脱出来,专注于业务逻辑实现。
2557 0
|
6月前
|
前端开发 Java 微服务
《深入理解Spring》:Spring、Spring MVC与Spring Boot的深度解析
Spring Framework是Java生态的基石,提供IoC、AOP等核心功能;Spring MVC基于其构建,实现Web层MVC架构;Spring Boot则通过自动配置和内嵌服务器,极大简化了开发与部署。三者层层演进,Spring Boot并非替代,而是对前者的高效封装与增强,适用于微服务与快速开发,而深入理解Spring Framework有助于更好驾驭整体技术栈。
|
6月前
|
XML JSON Java
【SpringBoot(三)】从请求到响应再到视图解析与模板引擎,本文带你领悟SpringBoot请求接收全流程!
Springboot专栏第三章,从请求的接收到视图解析,再到thymeleaf模板引擎的使用! 本文带你领悟SpringBoot请求接收到渲染的使用全流程!
524 3
|
存储 Java 文件存储
微服务——SpringBoot使用归纳——Spring Boot使用slf4j进行日志记录—— logback.xml 配置文件解析
本文解析了 `logback.xml` 配置文件的详细内容,包括日志输出格式、存储路径、控制台输出及日志级别等关键配置。通过定义 `LOG_PATTERN` 和 `FILE_PATH`,设置日志格式与存储路径;利用 `&lt;appender&gt;` 节点配置控制台和文件输出,支持日志滚动策略(如文件大小限制和保存时长);最后通过 `&lt;logger&gt;` 和 `&lt;root&gt;` 定义日志级别与输出方式。此配置适用于精细化管理日志输出,满足不同场景需求。
3064 1
|
前端开发 安全 Java
Spring Boot 便利店销售系统项目分包设计解析
本文深入解析了基于Spring Boot的便利店销售系统分包设计,通过清晰的分层架构(表现层、业务逻辑层、数据访问层等)和模块化设计,提升了代码的可维护性、复用性和扩展性。具体分包结构包括`controller`、`service`、`repository`、`entity`、`dto`、`config`和`util`等模块,职责分明,便于团队协作与功能迭代。该设计为复杂企业级应用开发提供了实践参考。
461 0
|
7月前
|
Java 数据库 数据安全/隐私保护
Spring Boot四层架构深度解析
本文详解Spring Boot四层架构(Controller-Service-DAO-Database)的核心思想与实战应用,涵盖职责划分、代码结构、依赖注入、事务管理及常见问题解决方案,助力构建高内聚、低耦合的企业级应用。
1503 1
|
9月前
|
前端开发 Java 数据库连接
SpringBoot参数校验底层原理和实操。深度历险、深度解析(图解+秒懂+史上最全)
SpringBoot参数校验底层原理和实操。深度历险、深度解析(图解+秒懂+史上最全)
SpringBoot参数校验底层原理和实操。深度历险、深度解析(图解+秒懂+史上最全)
|
9月前
|
机器学习/深度学习 XML Java
【spring boot logback】日志logback格式解析
在 Spring Boot 中,Logback 是默认的日志框架,它支持灵活的日志格式配置。通过配置 logback.xml 文件,可以定义日志的输出格式、日志级别、日志文件路径等。
1735 5
|
9月前
|
Java 关系型数据库 数据库连接
Spring Boot项目集成MyBatis Plus操作PostgreSQL全解析
集成 Spring Boot、PostgreSQL 和 MyBatis Plus 的步骤与 MyBatis 类似,只不过在 MyBatis Plus 中提供了更多的便利功能,如自动生成 SQL、分页查询、Wrapper 查询等。
953 2

推荐镜像

更多
  • DNS