의존성 추가
implementation 'org.springframework.boot:spring-boot-starter-validation'
User
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
@Size(min = 2)
private String name;
@Past
private Date joinDate;
}
@Past 애너테이션은 회원 가입 날짜가 현재 시간과 현재 시간 이전의 날짜만 올 수 있고 미래 데이터는 입력할 수 없도록 지정해주는 기능을 함UserController
@PostMapping("/users")
public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
User savedUser = service.save(user);
URI location = ServletUriComponentsBuilder.fromCurrentRequest() // 현재 가지고 있는 Request 사용
.path("/{id}") // 반환 시 URI 뒤에 /{id} 추가
.buildAndExpand(savedUser.getId()) // {id}에 savedUser.getId() 값을 넣어줌
.toUri();
return ResponseEntity.created(location).build();
}
@Valid 애너테이션은 사용자가 전달하는 user 값을 Validation 체크를 하는 기능

과거 시간은 성공

미래 시간 실패
CustomizedResponseEntityExceptionHandler
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatusCode status,
WebRequest request) {
ExceptionResponse exceptionResponse = new ExceptionResponse(
new Date(), "Validation Failed", ex.getBindingResult().toString()
);
return new ResponseEntity<>(exceptionResponse, HttpStatus.BAD_REQUEST);
}
}
ResponseEntityExceptionHandler 클래스에 있던 handleMethodArgumentNotValid() 메서드를 오버라이딩 해준다. 오버라이딩시 파라미터 타입이 다를 경우 오류가 발생하는 것을 주의해야 한다.

@Size(message=" ") 로 유효성 메시지 추가
User
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
@Size(min = 2, message = "Name은 2글자 이상 입력해주세요.")
private String name;
@Past
private Date joinDate;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
@Size(min = 2, message = "Name은 2글자 이상 입력해주세요.")
private String name;
@Past
private Date joinDate;
private String password;
private String ssn;
}
UserDaoService
// 데이터베이스에 3개의 데이터가 들어 있다고 가정
static {
users.add(new User(1, "roxy", new Date(), "pass1", "701010-1111111"));
users.add(new User(2, "yujin", new Date(), "pass2", "801010-2222222"));
users.add(new User(3, "kyj", new Date(), "pass3", "901010-3333333"));
}

사용자를 조회하자 비밀번호과 주민번호가 그대로 노출된다.
@JsonIgnore
private String password;
@JsonIgnore
private String ssn;
@JsonIgnoreProperties(value={"filed", "filed"}) 로 일괄 처리도 가능
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(value = {"password", "ssn"})
public class User {
private Integer id;
@Size(min = 2, message = "Name은 2글자 이상 입력해주세요.")
private String name;
@Past
private Date joinDate;
private String password;
private String ssn;
}
