Do I need a separate object for every @RequestBody in Spring Boot

Viewed 4631

So far I have done one (REST) project using Spring Boot and liked it a lot. The one thing I found to be somewhat devious was my understanding of @RequestBody.

Suppose I have the POST method below to login a user. My user entity may contain attributes other than just the username and password I'd like the post-request to have. In this case I saw no other option but to make an extra object (LoginRequest) to hold the data for the incoming data.

@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> login(@RequestBody LoginRequest request) {
        User p = null;
        if (request != null) {
            p = User.login(request.getEmail(), request.getPassword()); // validates and returns user if exists
            if (p != null){
                return new ResponseEntity<User>(p, HttpStatus.OK);
            }
        }

        throw new IllegalArgumentException("Password or email incorrect");
    }

Similarly, I'd like the @ResponseBody to return a minimized version of the User object where for example the password is excluded.

What are some of the standard approaches to this issue? Do I really have to make a separate object for every 'json-view'? I did some REST stuff in python before and here I would just have a Dictionary containing the request attributes. Any similar approaches?

2 Answers
Related