16

I am using @RestControllers 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 ?

osama yaccoub
  • 1,884
  • 2
  • 17
  • 47

2 Answers2

43

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());
Devendra Singh
  • 640
  • 6
  • 12
6

I have change your code please check it

DTO Class

public class DTO1 {


private String idNumber;
private String applicationId;

public String getIdNumber() {
    return idNumber;
}

public void setIdNumber(String idNumber) {
    this.idNumber = idNumber;
}

public String getApplicationId() {
    return applicationId;
}

public void setApplicationId(String applicationId) {
    this.applicationId = applicationId;
}

}

Rest Controller Method

@RequestMapping(value="/requestotp",method = RequestMethod.POST) 
public String requestOTP( @RequestBody DTO1 dto){
    System.out.println(dto.getApplicationId()+"  (------)  "+dto.getIdNumber());
    return "";
}

Request Type -- application/json {"idNumber":"345","applicationId":"64536"}

OR

@RequestMapping(value="/requestotp",method = RequestMethod.POST) 
public String requestOTP( @RequestBody String dto){
    System.out.println(dto);
    return "";
}