Reputation: 2243
In a Spring Boot application I have the following method signature in a Controller
:
@PostMapping(value="/borrow")
public ResponseEntity<Void> postBorrowBook(@RequestBody String personId,
@RequestBody String bookId) {
LOG.info(RESTController.class.getName() + ".postBorrowBook() method called.");
...
return new ResponseEntity<Void>(HttpStatus.OK);
}
I want to get the values of the two parameters from the RequestBody
.
Can anyone let me know how this be done if the request I am making is JSON as follows:
{"personId":"207","bookId":"5"}
I am currently receiving:
{
"timestamp": "2018-06-17T20:59:37.330+0000",
"status": 400,
"error": "Bad Request",
"message": "Required request body is missing: public org.springframework.http.ResponseEntity<java.lang.Void> com.city2018.webapps.code.controller.RESTController.postBorrowBook(java.lang.String,java.lang.String)",
"path": "/rest/borrow/"
}
I already have the following working in a similar scenario for simple non-REST requests:
@RequestMapping(value="/borrow", method=RequestMethod.POST)
public String postBorrowBook(@RequestParam("personId") String personId,
@RequestParam("bookId") String bookId,
Model model) {
LOG.info(PersonController.class.getName() + ".postBorrowBook() method called.");
Upvotes: 3
Views: 16919
Reputation: 67
You can also try another . e.g. @RequestBodyParam
@RequestMapping(value = "/saveData", headers="Content-Type=application/json", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Boolean> saveData(@RequestBodyParam String source,@RequestBodyParam JsonDto json) throws MyException {
...
}
https://github.com/LambdaExpression/RequestBodyParam
Upvotes: -1
Reputation: 186
First you should define a POJO class as:
public class BorrowBookEntity{ public String personId; public String bookId; }
Then you rely on spring to get the value as:
@PostMapping("/request")
public ResponseEntity<Void> postController(
@RequestBody BorrowBookEntity borrowBookEntity) {
...
Upvotes: 0
Reputation: 530
You can declare a POJO with 2 fields (personId and bookId) and change your signature as follow:
@PostMapping(value="/borrow")
public ResponseEntity<Void> postBorrowBook(@RequestBody RequestDTO requestBody) {
requestBody.getPersonId();
requestBody.getBookId();
...
}
Upvotes: 4