Kotlin을 사용한 Spring Boot 개발기 - Controller (@requestBody, Dto 생성하기) Spring Boot with Kotlin - Controller (@RequestBody, Creating DTOs)
Last time, I covered content related to GET requests. This time, I’ll briefly summarize while working with POST.
POST in SpringBoot Kotlin
Similarly, I’ll be using this inside a controller created with the @RestController annotation.
I worked on the same controller where I created the GET APIs. Rather than needing a lot of work, the goal is to try out requestBody, so let’s keep it simple.
Let’s use the @RequestBody annotation to receive the data from the request body.
Creating a DTO
To receive JSON data, let’s create a data class that matches the structure of the JSON data.
When creating DTOs in the previous Spring with Java, I remember lining up Lombok annotations above the DTO.

Things like these… I remember lining up annotations that included getters, setters, toString() to convert each data to a string, and so on.
In Kotlin, you don’t need any of that - just declaring a Kotlin Data Class automatically generates all of these for you.

Create a package in the same structure as the controller to create the DTO.
As shown below, add data in front of the Kotlin class and pay attention to the parentheses.
package com.example.linkwithbackend.dto
data class UserDto(
val id: Long,
val name: String,
val email: String,
val password: String
)
Since this is just for testing, I’m not sure what information will go in, but I’ve simply put together a UserDto.
Actually, I included the id thinking about storing it in the database, but when users actually POST, the id value won’t be included.
Creating the Controller
I wrote this in the same controller that contained the GetMapping from before.
@PostMapping()
fun createUser(@RequestBody user:UserDto): String {
println("#########################")
println(user.email)
println(user.name)
println(user.password)
println("#########################")
/*
Could create user registration logic here
*/
return "Hello ${user.name}"
}
I used the @RequestBody annotation to look at the POST body data, and the incoming data format matches the UserDto class we created earlier.
If you make a request like below:

You can see the data is output correctly like this:

You don’t have to provide all the data included in UserDto exactly as is, and you can also include data that doesn’t exist in the DTO.
However, our smart @RequestBody only extracts the data that exists within the DTO.
댓글남기기