gpt4 book ai didi

java - Spring 启动 : Can I post multiple objects as multiple @RequestParams to a REST service?

转载 作者:行者123 更新时间:2023-11-29 09:51:46 26 4
gpt4 key购买 nike

我使用 Spring Boot 使用单个资源构建了玩具 REST 服务,如下所示:

@RestController
@RequestMapping("/checkout")
public class CheckoutRestController {

@PostMapping("/book")
public boolean buyBook(@RequestParam CreditCard creditCard, @RequestParam ShippingAddress shippingAddress) {
return true;
}
}

CreditCardShippingAddress 都是我编写的 POJO(普通旧 Java 对象)。

我已尝试使用此有效负载发布到此端点:

{
"creditCard" : {
"nameOnCard":"foo",
"number":12345678,
"expiryMonth":12,
"expiryYear":2018,
"ccv":100
},
"shippingAddress" : {
"steert":"foor",
"houseNumber":"1a",
"city":"bar",
"state":"bazz",
"country":"buzz",
"zipCode":"booz"
},
}

但是我得到一个错误:

{
"timestamp": "2018-03-13T11:36:52.745+0000",
"status": 400,
"error": "Bad Request",
"message": "Required CreditCard parameter 'creditCard' is not present",
"path": "/checkout/book"
}

我知道一个解决方法是将两个 POJO 包装在一个请求包装器中,但我宁愿不这样做,除非我真的必须这样做。

是否可以发布两个@RequestParam 注解的对象?如果是这样,JSON 会是什么样子?

最佳答案

@RequestParam参数是query参数,不是body参数。

这意味着您的方法:

@PostMapping("/book")
public boolean buyBook(@RequestParam CreditCard creditCard, @RequestParam
ShippingAddress shippingAddress) {

return true;
}

需要以下请求:

POST /checkout/book?creditCard=<...>&shippingAddress=<...>

但是,Spring 不知道如何将 String 查询参数转换为 CreditCardShippingAddress

您可以通过实现Converter 来解决这个问题,如下所示:

public class StringToCreditCardConverter implements Converter<String, CreditCard> {

@Override
public CreditCard convert(String source) {
<...>
}
}

但是,我不推荐这样做,因为它不是请求主体的标准,并且会导致很多困惑和可维护性问题。

相反,推荐的方式如下:

@PostMapping("/book")
public boolean buyBook(@RequestBody BookCreationRequest bookCreationRequest) {
CreditCard creditCard = bookCreationRequest.getCreditCard();
ShippingAddress shippingAddress = bookCreationRequest.getShippingAddress();
...
}

bookCreationRequest 包含 CreditCardShippingAddress 字段(注意:您可以使用例如 lombok 来减少样板代码):

public class BookCreationRequest {
private ShippingAddress shippingAddress;
private CreditCredit creditCard;

public ShippingAddress getShippingAddress() {...}
public CreditCard getCreditCard() {...}

public BookCreationRequest(ShippingAddress shippingAddress, CreditCard creditCard) {
this.creditCard = creditCard;
this.shippingAddress = shippingAddress;
}

然后期望请求 JSON 如下:

POST /checkout/book
Payload:
{
"creditCard": {
...
},
"shippingAddress": {
...
}
}

注意一个请求中只能有一个@RequestBody参数。

关于java - Spring 启动 : Can I post multiple objects as multiple @RequestParams to a REST service?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49255224/

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