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

So far I have done one project (REST) ​​using Spring Boot and really enjoyed it. The only thing that seemed somewhat insidious to me was my understanding @RequestBody.

Suppose I have a POST method below to log into a user’s system. My user object may contain attributes other than the username and password that I need for a subsequent request. In this case, I did not see any other option than to make an additional object (LoginRequest) for storing data for 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 would like to @ResponseBodyreturn a minimized version of the User object, where, for example, the password is excluded.

? "json-view"? REST python, , . ?

+4
2

1) ,

2) (/ ), DTO

3) , , DTO, , , Map - JSON , :

@RequestMapping(method = RequestMethod.POST)
    public Map<String, Object> login(@RequestParam Integer p1) {
        Map<String, Object> map = new HashMap<>();
        map.put("p1", p1);
        map.put("somethingElse", "456");
        return map;
    }

JSON:

{
  "p1": p1value,
  "somethingElse": "456"
}

3- , , . .

+2

, , -
1. , . .
2. (DTO). , , , .

, DTO . , DTO , . . API .

+2

Source: https://habr.com/ru/post/1677860/


All Articles