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
관리 메뉴

개발자되기 프로젝트

POST 본문

1. @PostMapping

@RestController
@RequestMapping("/api")
class PostApiController {

    @PostMapping("/post-mapping")
    fun postMapping(): String{
        return "post-mapping"
    }

}

 

 

2. @RequestMapping 사용 시


@RequestMapping(method = [RequestMethod.POST], path = ["/request-mapping"])
fun requestMapping(): String {
    return "post-mapping2"
}

 

 

 

3. @RequestBody


HTTP 메세지 바디에 담겨있는 json data를 객체로 받기 위해서 @RequestBody 사용.

 

HTTP 메시지 컨버터

HTTP API처럼 JSON 데이터를 HTTP 메시지 바디에서 직접 읽거나 쓰는 경우 HTTP 메시지 컨버터를 사용하면 편리하다. 1. @ResponseBody 사용 원리 @ResponseBody 를 사용 HTTP의 BODY에 문자 내용..

bsh-developer.tistory.com

//json <-> object: object Mapper, 스프링에서 기본적으로 사용
@PostMapping("/post-mapping/object")
fun postMappingObject(@RequestBody userRequest: UserRequest): UserRequest {
    println(userRequest)
    return userRequest
}

 

요청 메세지 바디에 json 을 넣어서 보냈고, 응답도 확인 가능.

 

 

4. 주의사항 : Naming Convention


Naming Convention에 따른 문제가 발생할 수 있다.

기본적으로 Kotlin은 Camel case를 사용한다.(phoneNumber)

하지만 대부분 rest api이 json 형태는 snake case가 많다.(phone_number)

따라서 요청 메시지 바디에 snake case가 있는 경우 kotlin에서 매칭을 못한다.

 

phoneNumber가 null 이다.

 

이에 대한 대비도 다 되어 있다.

 

전에 만들어둔 data class에 해당하는 변수에 @JsonProperty를 적용하면 됨.

data class UserRequest(
    var name: String? = null,
    var age: Int? = null,
    var email: String? = null,
    var address: String? = null,
    
    @JsonProperty("phone_number")
    var phoneNumber: String? = null //phone_number: snake case
)

@JsonProperty(value)를 적용해 주면 해당 data는 message body에 value로 적용된다.

(요청: phone_number -> kotlin: phoneNumber -> 응답: phone_number)

아 그런데 매번 적어주기 귀찮은데?

 

해당 class에 @JsonNaming을 적용해주면 지정한 클래스로 Json 의 naming 규칙을 정할 수 있다.

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy::class)
data class UserRequest(
    var name: String? = null,
    var age: Int? = null,
    var email: String? = null,
    var address: String? = null,

    //@JsonProperty("phone_number")
    var phoneNumber: String? = null //phone_number: snake case
)

 

 

5. GitHub


 

GitHub - bsh6463/KotlinSpring: GET

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

github.com

 

'인프런 > [인프런] Kotlin으로 개발하는 Spring Boot Web MVC' 카테고리의 다른 글

ResponseEntity, @ResponseBody  (0) 2022.04.24
DELETE  (0) 2022.04.24
PUT, Request Body, ResponseBody  (0) 2022.04.24
GET  (0) 2022.04.24
[인프런] Web 개론  (0) 2022.04.24
Comments