본문 바로가기
Spring Framework

@Valid 애너테이션 사용해서 값 검증하기

by 자유코딩 2019. 1. 17.

@Valid 애너테이션을 활용하면 입력 값을 검증하는 규칙을 만들 수 있다.

 

먼저 컨트롤러에 @Valid 애너테이션을 명시한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    @PostMapping
    public ResponseEntity createEvent(@RequestBody @Valid EventDto eventDto){ // 모델매퍼를 활용해서 EventDTO 를 Event 로 바꾼다.
//        Event event = Event.builder() 1. ModelMapper 를 사용하지 않는 방법
//                .name(eventDto.getName())
//                .description(eventDto.getDescription())
        //ModelMapper 를 사용하는 방법
        Event event = modelMapper.map(eventDto , Event.class); // 위에 사용하지 않는 방법은 많은 값을 입력한다. //ModelMapper 를 사용하면 이 1줄로 들어온 모든 값을 1세팅 할 수 있다.
 
        Event newEvent = this.eventRepository.save(event);
 
        URI createUri = linkTo(EventController.class).slash(newEvent.getId()).toUri();
        event.setId(10);
        return ResponseEntity.created(createUri).body(event);
    }
 
}
cs

 

@Requestbody 옆에 @Valid 라고 작성했다.

 

이제 EventDto 클래스에 검증규칙을 만든다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.example.api.events;
 
import lombok.*;
 
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
 
@Builder @NoArgsConstructor @AllArgsConstructor
@Getter @Setter
public class EventDto {
    @NotEmpty
    private String name;
    @NotEmpty
    private String description;
    @NotNull
    private LocalDateTime beginEnrollmentDateTime;
    @NotNull
    private LocalDateTime closeEnrollmentDateTime;
    @NotNull
    private LocalDateTime beginEventDateTime;
    @NotNull
    private LocalDateTime endEventDateTime;
    private String location; // location 값이 없다면 온라인 모임
    @Min(0)
    private int basePrice; // optional
    @Min(0)
    private int maxPrice; // optional
    @Min(0)
    private int limitOfEnrollment;
}
 
cs

 

@NotEmpty , @Notnull , @Min 과 같은 항목을 작성했다.

 

@NotEmpty 는 String 타입의 경우 값이 비어 있으면 안되는 것이다.

 

@Notnull 은 값이 null 이면 안되는 것이다.

 

@Min(0) 은 최소한 값이 0보다는 커야하는 것이다.

 

이렇게 적어두고 @Valid 를 사용하면 사용자가 값을 보냈을때 애너테이션의 규칙에 따라 검사한다.

 

 

댓글