![](/img/trans.png)
[英]How do I handle an unknown number of RequestParams in Spring Boot REST?
[英]Spring Rest - bind nested DTO object to @RequestParams
我想將 get 參數綁定到我的 DTO。 我的問題是映射我的 DTO 擁有的嵌套列表。
controller class:
@PostMapping(value = "test-endpoint")
public ResponseEntity<String> doStuff(@Valid @RequestParams MyDto myDto) {
// do stuff
}
父 DTO:
public class MyDto {
@NotNull
private String fieldA;
@Valid
@NotNull
private List<MyNestedDto> nestedDto;
}
嵌套 DTO:
public class MyNestedDto {
@NotNull
private String nestedFieldA;
@NotNull
private String nestedFieldB;
// more fields
}
我有一個向我的 controller 發送 POST 請求的服務。 請求無法更改,因此我不能使用@RequestBody
注釋。
請求如下所示:
http://localhost:8080/api/test-endpoint?nestedDto={"more":[{"nestedFieldA":"example","nestedFieldB":"example"}]}&fieldA=123
有沒有辦法綁定嵌套列表來獲取參數?
編輯*
注冊轉換器似乎不起作用,甚至沒有調用我的轉換器轉換方法。
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new MyConverter());
}
}
public class MyConverter implements Converter<String, MyDto> {
@Override
public MyDto convert(String source) {
// it never reaches there
ObjectMapper objectMapper = new ObjectMapper();
return null; // return null for testing purposes
}
}
public class AController {
private final ObjectMapper objectMapper;
private final Validator validator;
public AController(ObjectMapper objectMapper,Validator validator){
this.objectMapper = objectMapper;
this.validator = validator;
}
@PostMapping(value = "test-endpoint")
public ResponseEntity<String> doStuff(@RequestParam("nestedDto") String nestedDto) {
MyDto myDto = objectMapper.readValue(nestedDto);
Set<ConstraintViolation<MyDto>> constraintViolation =
validator.validate(myDto);
if (!constraintViolation.isEmpty()) {
throw new ConstraintViolationException(constraintViolation);
}
}
}
這是偽代碼,所以我只是寫它來演示如何解決問題。 如果你想要更優雅的方式,你必須改變請求,因為這里的請求是錯誤的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.