'Passing a DTO and other values in @RequestBody in Spring

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" : "[email protected]",
  "emailRepeat" : "[email protected]",
  "password" : "asdasd",
  "passwordRepeat" : "asdasd",
  "roleId" : 1
}

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



Solution 1:[1]

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

Solution 2:[2]

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

Solution 3:[3]

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 wtih json

{ "username": "usernameABC", "email" : "[email protected]", "emailRepeat" : "[email protected]", "password" : "asdasd", "passwordRepeat" : "asdasd", }

OR

you can also add roleId into your UserDto class

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Roon
Solution 2
Solution 3