Harsha Jayamanna
Harsha Jayamanna

Reputation: 2258

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?

Upvotes: 0

Views: 14961

Answers (3)

Amol Raje
Amol Raje

Reputation: 968

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

OR

you can also add roleId into your UserDto class

Upvotes: 0

Roon
Roon

Reputation: 81

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

Upvotes: 1

user2080225
user2080225

Reputation:

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

Upvotes: 0

Related Questions