0

I want a pass a dto and another value using the @RequestBody in spring. Something like shown in below,(This is my controller code)

public User createUser( @RequestBody @Validated UserDto userDto,@RequestBody Integer roleId ){
        return userService.createUser(userDto.getUsername(), userDto.getEmail(), userDto.getPassword(),roleId);
    }

Below is the json I'm sending via the post call.

{
  "username": "usernameABC",
  "email" : "abc@gmail.com",
  "emailRepeat" : "abc@gmail.com",
  "password" : "asdasd",
  "passwordRepeat" : "asdasd",
  "roleId" : 1
}

Is it possible to do this? or do I have to include the roleId in the dto itself?

Harsha Jayamanna
  • 2,148
  • 6
  • 25
  • 43

3 Answers3

1

You must include roleId in DTO. @RequestBody bind json into one Object. see this post.

Roon
  • 81
  • 1
  • 3
0

You should create a POJO that has the properties that match your JSON and then everything is easier, because spring knows how to convert the data. You don't need any @RequestBody stuff in your DB layer. Keep that stuff in the controller. Your DB layer should just accept POJOs to persist, and not even know if it's coming from a request or not. Could be test case for example.

Here's how i do it:

@RequestMapping(value = API_PATH + "/signup", method = RequestMethod.POST)
@OakSession
public @ResponseBody SignupResponse signup(@RequestBody SignupRequest req) {
    logRequest("signup", req);
    SignupResponse res = new SignupResponse();
    userManagerService.signup(req, res, false);
    return res;
}

Taken from here: (My project)

https://github.com/Clay-Ferguson/meta64/blob/master/src/main/java/com/meta64/mobile/AppController.java

0

try this

public User createUser( @RequestBody @Validated UserDto userDto,@RequestParam Integer roleId ){
    return userService.createUser(userDto.getUsername(), userDto.getEmail(), userDto.getPassword(),roleId);
}

for passing value from url use localhost:8085/user/user-api?roleId =45632 with json

{
  "username": "usernameABC",
  "email" : "abc@gmail.com",
  "emailRepeat" : "abc@gmail.com",
  "password" : "asdasd",
  "passwordRepeat" : "asdasd",
}

OR

you can also add roleId into your UserDto class

bst
  • 75
  • 1
  • 8
Amol Raje
  • 928
  • 3
  • 9
  • 16
  • I knew this could be possible. I want to know if can pass all on the request body. – Harsha Jayamanna Nov 25 '17 at 09:30
  • yes you can ..then just create your `UserDto` with `roleId` property and other and pass as `@RequestBody` – Amol Raje Nov 25 '17 at 09:34
  • see this link https://stackoverflow.com/questions/27189730/multiple-requestbody-values-in-one-controller-method ...You cannot use two @RequestBody as it can bind to a single object only (the body can be consumed only once). – Amol Raje Nov 25 '17 at 09:38