파라미터 체크하기(hibernate validator)

By | 2020년 3월 22일
Table of Contents

파라미터 체크하기(hibernate validator)

개발환경

  • Spring Boot 2.1.x
  • Gradle 4.10.2

build.gradle 수정

build.gradle

......
dependencies {
    // ......
    compile('org.hibernate.validator:hibernate-validator')
    // ......
}
......

DTO 파라미터 체크하기

import javax.validation.constraints.NotEmpty;

@Getter
@NoArgsConstructor
public class PostsSaveRequestDto {

    @Range(min=1, max=20)
    @NotEmpty(message = "제목은 필수 입니다")
    private String title;
    @NotEmpty(message = "내용은 필수 입니다")
    private String content;
    @NotEmpty(message = "작성자는 필수 입니다")
    private String author;

    @NotEmpty(message = "비밀번호는 필수 입니다")
    @Pattern(regexp = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})", message = "비밀 번호는 6~20자리로 숫자와 특수 문자가 포함된 영문 대소문자로 입력해 주세요")
    private String password;

    // ......
}

@NotEmpty 어노테이션을 추가함으로 공백이 입력되는 것을 방지합니다.

정규식을 이용해 보다 복잡한 체크를 할 수 있습니다.

import javax.validation.Valid;

@RequiredArgsConstructor
@RestController
public class PostsApiController {

    private final PostsService postsService;

    @PostMapping("/api/v1/posts")
    public Long save(@Valid @RequestBody PostsSaveRequestDto postsSaveRequestDto) {
        return postsService.save(postsSaveRequestDto);
    }

    // ......
}

@Valid 파라미터를 추가하여 파라미터 체크를 시작합니다.

        $.ajax({
            type : 'POST',
            url : '/api/v1/posts',
            dataType : 'json',
            contentType : 'application/json; charset=utf-8',
            data : JSON.stringify(data)
        }).done(function() {
            alert('글이 등록되었습니다.');
            window.location.href = '/';
        }).fail(function(error) {
            //alert(JSON.stringify(error));
            if (error.status == 400) {
                alert(error.responseJSON.errors[0].defaultMessage);
            } else {
                alert('알 수 없는 오류입니다.' + error.status);
            }
        });

RestController 이기에 json 으로 오류메시지가 반환됩니다.

@PathVariable 체크하기

@PathVariable 에 대해서는 @Valid 가 지원되지 않습니다. 대신, 아래와 같이 정규식을 이용해 파라미터 체크를 할 수 있고, 허용되지 않는 데이타가 전달되었을 때, 404 에러를 반환합니다.

    @GetMapping("/posts/update/{id:[0-9]+}")
    public String postsUpdate(@PathVariable Long id, Model model) {
        PostsResponseDto dto = postsService.findById(id);
        model.addAttribute("post", dto);

        return "posts-update";
    }

답글 남기기