SpringBoot - 获取POST请求参数详解(附样例:表单数据、json、数组、对象)

本文详细介绍了SpringBoot如何处理POST请求的各种参数,包括Form表单数据、字符串文本、JSON数据的接收方法。通过实例展示了如何使用Map、对象、数组、默认值以及处理带有前缀的参数。同时,讲解了接收Text文本数据和JSON对象转换为Bean对象的方式。
摘要由CSDN通过智能技术生成

上一篇:SpringBoot - 获取Get请求参数详解(附样例:非空、默认值、数组、对象)

一、接收 Form 表单数据

1,基本的接收方法
(1)编写hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/hello" enctype="multipart/form-data" method="post">
    name: <input type="text" name="name">
    age: <input type="text" name="age">
    <input type="submit">
</form>
</body>
</html>

(2)下面样例 Controller 接收 form-data 格式的 POST 数据:

package com.example.demo;
 
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class HelloController {
   
    @PostMapping("/hello")
    public String hello(@RequestParam("name") String name,
                        @RequestParam("age") Integer age) {
   
        return "name:" + name + "\nage:" + age;
    }
}

(3)测试结果:
在这里插入图片描述
在这里插入图片描述
2,参数没有传递的情况
(1)如果没有传递参数 Controller 将会报错,这个同样有如下两种解决办法:
使用 required = false 标注参数是非必须的。
使用 defaultValue 给参数指定个默认值。

package com.example.demo;
 
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class HelloController {
   
    @PostMapping("/hello")
    public String hello(@RequestParam(name = "name", defaultValue = "xxx") String name,
                        @RequestParam(name 
  • 3
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值