boot spring 接口接收数据_SpringBoot - 获取POST请求参数详解(附样例:表单数据、json、数组、对象)...

在前文中我介绍了 Controller 如何接收通过 GET 方式传递过来的参数(点击查看),下面接着演示如何接收通过 POST 方式传递过来的参数。

一、接收 Form 表单数据

1,基本的接收方法

(1)下面样例 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;

}

}

(2)下面是一个简单的测试样例:

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 = "age", required = false) Integer age) {

return "name:" + name + "\nage:" + age;

}

}

(2)下面是一个简单的测试样例:

3,使用 map 来接收参数

(1)Controller 还可以直接使用 map 来接收所有的请求参数:

package com.example.demo;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.RestContro

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值