Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

JSR-380 Bean Validation 본문

인프런/[인프런] Kotlin으로 개발하는 Spring Boot Web MVC

JSR-380 Bean Validation

Seung__ 2022. 4. 24. 23:45

1. 의존성 추가


implementation("org.springframework.boot:spring-boot-starter-validation")

 

 

2. 파라미터에 적용


Bean Validator를 파라미터에 사용하기 위해서는 class에 @Validated를 적용해야 한다.

@RestController
@RequestMapping("/api")
@Validated //얘를 적용해야 하위에 있는 validation Annotation이 동작함.
class DeleteApiController {
    // 1. path variable

    // 2. request param

    @DeleteMapping("/delete-mapping")
    fun deleteMapping(
        @RequestParam(value = "name")
        @NotNull
        @Size(min=2, max=5)
        _name: String,

        @NotNull(message = "age값이 누락되었습니다.")
        @Min(value = 20, message = "age는 20보다 커야합니다.")
        @RequestParam(name = "age") _age: Int
    ): String {
        println(_name)
        println(_age)

        return _name+" "+_age
    }

    @DeleteMapping("/delete-mapping/name/{name}/age/{age}")
    fun deleteMappingPath(
        @PathVariable(value = "name")
        @NotNull
        @Size(min=2, max=5)
        _name: String,

        @NotNull(message = "age값이 누락되었습니다.")
        @Min(value = 20, message = "age는 20보다 커야합니다.")
        @PathVariable(name = "age") _age:Int
    ): String {
        println(_name)
        println(_age)

        return _name+" "+_age
    }
}

 

 

 

3. Bean 검증


Kotlin에서 data class에 annotation을 적용하기 위해서는 @field: annotaion 과 같은 형태로 작성해야 한다.

data class UserRequest(


    @field:NotEmpty
    @field:Size(min=2, max=8)
    var name: String? = null,

    @field:PositiveOrZero
    var age: Int? = null,

    @field:Email
    var email: String? = null,

    @field:NotBlank
    var address: String? = null,
    
    @field:Pattern(regexp = "^\\d{2,3}-\\d{3,4}-\\d{4}\$") //정규식
    var phoneNumber: String? = null //phone_number: snake case
)

사용하고자 하는 곳에서 @Valid를 적용해 주면 됨.

@PutMapping("/put-mapping/object")
fun putMappingObject(@Valid @RequestBody userRequest: UserRequest): UserResponse {

    // 0. userResponse
   return  UserResponse().apply {
        // 1. result
        this.result =  Result().apply {
            this.resultCode = "OK"
            this.resultMessage = "성공"
        }
    }.apply {
        // 2. description
        this.description = "~~~~~~~"
    }.apply {
        // 3. user mutable list
        val userList = mutableListOf<UserRequest>()

        userList.add(userRequest)

        userList.add(UserRequest().apply {
            this.name = "A"
            this.age = 10
            this.email = "A.com"
            this.address = "a address"
            this.phoneNumber = "01011111"
        })

        userList.add(UserRequest().apply {
            this.name = "B"
            this.age = 20
            this.email = "B.com"
            this.address = "b address"
            this.phoneNumber = "01011111"
        })

       this.user = userList
    }
}

 

이름을 짧게 가져가는 경우 에러 발생.

 

 

 

4. BindingResult


 

BindingResult1

지금부터 스프링이 제공하는 검증 오류 처리 방법 중 BindingResult를 알아보자. 1. 변경 전 @PostMapping("/add") public String addItem(@ModelAttribute Item item, RedirectAttributes redirectAttributes, Mo..

bsh-developer.tistory.com

 

 

BindingResult2

1. BindingResult?? 스프링이 제공하는 검증 오류를 보관하는 객체이다. 검증 오류가 발생하면 여기에 보관하면 된다. BindingResult 가 있으면 @ModelAttribute 에 데이터 바인딩 시 오류가 ..

bsh-developer.tistory.com

BindingResult는 binding하는 객체의 binding결과를 담고 있다.

 

이전에는 binding시 에러가 발생하면 메서드가 호출되지도 않음.

 

BindingResult를 사용하는 경우 메서드 호출이 가능하다.

 

이를 통해 메서드 내부에서 예외 처리를 할 수 있음.

 

    @PutMapping("/put-mapping/object")
    fun putMappingObject(@Valid @RequestBody userRequest: UserRequest, bindingResult: BindingResult): ResponseEntity<String>? {

        if (bindingResult.hasErrors()){
            // 500 err
            val msg = StringBuilder()
            bindingResult.allErrors.forEach{
                val field = it as FieldError
                val message = it.defaultMessage
                msg.append(field.field.toString() + " : " + message +"\n")
            }
            return ResponseEntity.badRequest().body(msg.toString())
        }
        return ResponseEntity.ok("")
    }

 

 

 

5. @AssertTrue


검증해야 할 필드에 적용할 validation annotaion이 없는 경우가 있다.

이 경우 검증 메서드를 직접 만들 필요가 있다.

메서드를 만들고 @AssertTrue를 적용하면 validation 진행 시 해당 메서드도 실행이 된다.

data class UserRequest(


    @field:NotEmpty
    @field:Size(min=2, max=8)
    var name: String? = null,

    @field:PositiveOrZero
    var age: Int? = null,

    @field:Email
    var email: String? = null,

    @field:NotBlank
    var address: String? = null,

    @field:Pattern(regexp = "^\\d{2,3}-\\d{3,4}-\\d{4}\$") //정규식
    var phoneNumber: String? = null, //phone_number: snake case

    var createdAt: String? = null //yyyy-MM-dd HH:mm:ss
){
    @AssertTrue(message = "생성 일자의 패턴은 yyyy-MM-dd HH:mm:ss여야 합니다.") //validation할 때 해당 메서드 실행됨.
    private fun isValidCreatedAt(): Boolean{

        return try {
            LocalDateTime.parse(this.createdAt, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
            true
        }catch (e:Exception){
            false
        }
    }
}

 

6. GitHub


 

GitHub - bsh6463/KotlinSpring: GET

GET. Contribute to bsh6463/KotlinSpring development by creating an account on GitHub.

github.com

 

Comments