[Spring] ๋ชจ๋ธ ๊ฒ€์ฆ(validation)

1. Overview

Spring Boot๋ฅผ ํ†ตํ•œ REST API ์ƒ˜ํ”Œ์˜ˆ์ œ๋ฅผ ํ†ตํ•ด์„œ, ๋„๋ฉ”์ธ ๊ฐ์ฒด๋ฅผ validation ํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์•Œ์•„๋ณด์ž. ๊ธฐ๋ณธ ์ „์ œ ์กฐ๊ฑด์€, ์œ ์ €๊ฐ€ ๋„˜๊ธฐ๋Š” ๋ชจ๋“  ๋ฐ์ดํ„ฐ๋Š” ์‹ ๋ขฐํ• ์ˆ˜ ์—†๋‹ค. ๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— ๋ชจ๋“  ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ˜๋“œ์‹œ ๊ฒ€์ฆํ•ด์•ผ ํ•œ๋‹ค. ๋Œ€๊ฒŒ validation์€ Post์š”์ฒญ์‹œ, @RequestBody์— ๋‹ด๊ธธ ๊ฐ์ฒด์— ๋Œ€ํ•ด์„œ ๊ฒ€์ฆํ•˜๋Š”๊ฒŒ ์ผ๋ฐ˜์ ์ด๋‹ค.

2. User Domain

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NotBlank(message = "name is required")
    private String name;

    @NotBlank(message = "email is required")
    private String email;

}

3. Implement RestControllor

@RestController
public class UserController {

    @PostMapping("/users")
    public ResponseEntity<String> addUser(@Valid @RequestBody User user) {
        return ResponseEntity.ok("user is valid");
    }
}

POST ์š”์ฒญ์‹œ, ํด๋ผ์ด์–ธํŠธ๊ฐ€ ๋„˜๊ธฐ๋Š” ๊ฐ’๋“ค์€ ๊ธฐ๋ณธ์ ์œผ๋กœ ์‹ ๋ขฐํ•  ์ˆ˜ ์—†๋‹ค. ๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— validation์„ ๋ฐ˜๋“œ์‹œ ํ•ด์•ผ ํ•œ๋‹ค. @Valid ์–ด๋…ธํ…Œ์ด์…˜๋งŒ ๋ถ™์ด๋ฉด, Spring Boot๋Š” JSR303 ๊ตฌํ˜„์ฒด(Hibernate Validator)๋ฅผ ์‚ฌ์šฉํ•ด์„œ argument๊ฐ’์„ validate๋ฅผ ์ง„ํ–‰ํ•œ๋‹ค.

4. Exception Handling

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleValidationExceptions(MethodArgumentNotValidException ex) {
    Map<String, String> errors = new HashMap<>();
    ex.getBindingResult().getAllErrors().forEach(
            (error) -> {
                String fieldName = ((FieldError) error).getField();
                String errorMessage = error.getDefaultMessage();
                errors.put(fieldName, errorMessage);
            }
    );

    return errors;
}

@ExceptionHandler๋ฅผ ํ†ตํ•ด์„œ MethodArgumentNotValidException๋ฅผ ํ•ธ๋“ค๋ง ํ•œ๋‹ค. errors map์— ๋‹ด์•„์„œ ๋ฐ˜ํ™˜ํ•˜๋ฉด, @RestController์˜ @ResponseBody๋ฅผ ํ†ตํ•ด์„œ JSON ๊ฐ’์œผ๋กœ ๋ฆฌํ„ด๋œ๋‹ค.

5. TEST

PostMan์œผ๋กœ POST /users์˜ name๊ณผ email ํ•„๋“œ ์—†์ด ๋นˆ Json์„ ๋„˜๊ธฐ๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋‚˜์˜จ๋‹ค.

{
  "name": "name is required",
  "email": "email is required"
}

์ƒ๊ฐํ•ด๋ณผ ๊ฒƒ๋“ค

์—ฐ๊ด€ ํฌ์ŠคํŠธ