티스토리 뷰

@PathVariable

  • @PathVariable 파라메터를 사용하면 아래와 같이 URI의 일부를 변수로 전달할 수 있다.
@GetMapping("/bars/{barId}")
fun getBar(@PathVariable(value = "barId") barId: Optional<String>)
  • @PathVariable 파라메터는 생략이 불가능하다. 생략할 경우 404 Not Found 오류로 분기된다. 생략을 허용하려면 아래와 같이 생략된 엔드포인트 URI를 추가하면 된다.
@GetMapping(value = ["/bars","/bars/{barId}"])
  • @PathVariable 파라메터 타입으로 Optional<>을 사용하면 옵셔널 체크를 좀 더 우아하게 표현할 수 있다. [관련 링크]
  • @PathVariable 파라메터 타입으로 Enum 클래스를 사용할 수 있다.
@PathVariable(value = "statusCd") statusCd: StatusCd
@PathVariable(value = "statusCd") statusCd: Optional<StatusCd>
  • Enum 클래스 사용시 주의점은 요청 URI에 대문자가 아닌 소문자로 입력시 ConversionFailedException 예외가 발생한다. 소문자도 인지하도록 하러면 아래와 같이 org.springframework.boot.convert.ApplicationConversionService 클래스를 별도로 등록해 주어야 한다. [관련 링크]
package com.jsonobject.example

import org.springframework.boot.convert.ApplicationConversionService
import org.springframework.context.annotation.Configuration
import org.springframework.format.FormatterRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer

@Configuration
class ConversionConfig : WebMvcConfigurer {

    override fun addFormatters(registry: FormatterRegistry) {
        ApplicationConversionService.configure(registry)
    }
}
  • Enum 클래스의 name으로 정의되지 않은 값이 전달될 경우 MethodArgumentTypeMismatchException 예외가 발생한다. 예외에 대한 적절한 오류 메시지를 응답하려면 아래와 같이 @ExceptionHandler을 작성하면 된다.
@ExceptionHandler(value = [MethodArgumentTypeMismatchException::class])
fun handleMethodArgumentTypeMismatchException(ex: Exception): ResponseEntity<Void> {

    return ResponseEntity.notFound().build()
}
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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
글 보관함