I am using @RestController
s with an application where all requests are POST
requests ... As I learned from this post , you can't map individual post parameters to individual method arguments, rather you need to wrap all the parameters in an object and then use this object as a method parameter annotated with @RequestBody
thus
@RequestMapping(value="/requestotp",method = RequestMethod.POST)
public String requestOTP( @RequestParam(value="idNumber") String idNumber , @RequestParam(value="applicationId") String applicationId) {
return customerService.requestOTP(idNumber, applicationId);
will not work with a POST
request of body {"idNumber":"345","applicationId":"64536"}
MY issue is that I have A LOT of POST
requests , each with only one or two parameters, It will be tedious to create all these objects just to receive the requests inside ... so is there any other way similar to the way where get request parameters (URL parameters) are handled ?
So basically, while @RequestBody maps entire user request (even for POST) to a String variable, @RequestParam does so with one (or more - but it is more complicated) request param to your method argument.
The handler for @RequestBody reads the body and binds it to the parameter. The handler for @RequestParam can then get the request parameter from the URL query string. The handler for @RequestParam reads from both the body and the URL query String.
@RequestBody : Annotation indicating a method parameter should be bound to the body of the HTTP request. @ResponseBody annotation can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).
If you don't add @RequestBody it will insert null values (should use), no need to use @ResponseBody since it's part of @RestController.
Yes there are two ways -
first - the way you are doing just you need to do is append these parameter with url, no need to give them in body. url will be like - baseurl+/requestotp?idNumber=123&applicationId=123
@RequestMapping(value="/requestotp",method = RequestMethod.POST)
public String requestOTP( @RequestParam(value="idNumber") String idNumber , @RequestParam(value="applicationId") String applicationId) {
return customerService.requestOTP(idNumber, applicationId);
second- you can use map as follows
@RequestMapping(value="/requestotp",method = RequestMethod.POST)
public String requestOTP( @RequestBody Map<String,Object> body) {
return customerService.requestOTP(body.get("idNumber").toString(), body.get("applicationId").toString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With