I was wondering what is the best way to pass a simple int[] array to a Spring Controller?
As of now it only worked when I am passing the values as a @RequestParam in the URL, however I would like to send them for example as a @RequestBody. How could I do that?
`
@PostMapping
public int acceptArray(@RequestParam int[] array) {
if (array == null || array.length == 0) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "You entered an empty array");
}
return arraySolver.arraySolver(array);
}
`
Since I am kinda new a more detailed explanation would be appreciated:)
Thank you in advance for the help.
You can achieve that by passing the multiple arguments as query params like show in below. The controller is taking array as input and sum the elements and returns that. That is why for [1,2,3] it outputs 6.
To send it as request body you can just follow below code.
@PostMapping
public int acceptArray(@RequestBody InputArrayRequest request) {
if (request.getArray() == null || request.getArray().length == 0) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "You entered an empty array()");
}
return arraySolver.arraySolver(array);
}
class InputArrayRequest {
private int[] array;
public int[] getArray() {
return array;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.