gpt4 book ai didi

Spring Boot - 如何在 HTTP Post api 中传递自定义值?

转载 作者:行者123 更新时间:2023-12-04 16:09:11 24 4
gpt4 key购买 nike

我是 Spring Boot 的新手,我很难理解如何传递数据。例如:

我想将这些数据传递到我的服务器:

{
"code", 1,
"name": "C01"
}

所以我总是创建一个自定义对象,将代码和名称作为属性来拥有这个 http post api?

@RequestMapping(value = "/new/", method = RequestMethod.POST)
public ResponseEntity<?> createOrder(@RequestBody CustomObject customObject){
...
}

我看到的另一个解决方案可以是这个,但我不能传递数字(int 代码),对吗?

@RequestMapping(value = "/new/{code}/{name}", method = RequestMethod.POST)
public ResponseEntity<?> createOrder(@PathVariable("code") int code, @PathVariable("name") String name) {
...
}

亲切的问候:)

最佳答案

你可以通过 codename作为PathVariable就像你的例子一样:

@RequestMapping(value = "/new/{code}/{name}")
public ResponseEntity<?> createOrder(@PathVariable("code") int code, @PathVariable("name") String name) {
...
}

A PathVariable根据文档,可以是 int 或 String 或 long 或 Date:

A @PathVariable argument can be of any simple type such as int, long, Date, etc. Spring automatically converts to the appropriate type or throws a TypeMismatchException if it fails to do so.

你也可以定义一个 PathVariable类型 Map<String, Object>像这样:

@RequestMapping(value = "/new/{code}/{name}")
public ResponseEntity<?> createOrder(@PathVariable("map") Map<String, Object> map) {
Integer code = (Integer) map.get("code");
String name = (String) map.get("name");
...
}

你甚至可以使用 @RequestParam并以 URL 查询参数的形式提供数据。

因此,可以通过多种方式将数据传递给 Spring MVC Controller (更多详细信息 in the docs ),但我认为发布 复杂数据的约定(我的意思是“复杂” more than a single piece of state) 是定义一个请求主体,其中包含该复杂状态的序列化形式,即您在问题的第一个示例中显示的内容:

@RequestMapping(value = "/new/", method = RequestMethod.POST)
public ResponseEntity<?> createOrder(@RequestBody CustomObject customObject){
...
}

关于Spring Boot - 如何在 HTTP Post api 中传递自定义值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46132536/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com