Kotlin을 사용한 Spring Boot 개발기 - Controller (@RequestParam, @PathVariable) Spring Boot with Kotlin - Controller (@RequestParam, @PathVariable)
Kotlin을 사용해서 SpringBoot를 개발 해 보려고 한다.
심심하기도 하고(?) 해서, Spring으로 다시 개발 프로젝트 하나 해보자! 라는 생각을 하게 되었고 만드는 김에 Kotlin으로 만들어보자 하는 생각이 들어서 시작을 해 보게 되었다.
두서가 없을 수 있지만, 개발하면서 찾아 보는 내용들을 정리해야겠다.
Spring Boot 와 Kotlin
세팅과 관련된 글은 이미 많은 분들이 작성 해 주셨기때문에 따로 적지 않으려고 한다. (다들 이미 너무 잘 정리 해주셨다)
LinkedIn 과 비슷한 프로젝트를 만들어 보려고 한다. 데모 프로젝트지만 많은 사람들을 연결 할 수 있는 경험들을 해 보고싶다.
Kotlin으로 Controller 작성하기
User와 관련 된 컨트롤러를 먼저 작성했다.

가장 기본이 되는 Application.kt가 들어있는 패키지 내에, Controller 패키지를 세팅하고 아래에 kotlin 파일을 만들었다.
테스트니까, GetMapping에서 인사를 해보자 - queryParam
컨트롤러로 뭘 할까 생각하다가 GetMapping으로 간단하게 테스트를 해 보자! 라는 생각이 들었다. GetMapping으로 GET 요청들을 받아주려고 했고, 들어오는 queryParam을 정해서 확인하는 코드를 작성했다.
query parameter를 받아주는 어노테이션은 @RequestParam 이다.
package com.example.linkwithbackend.controller
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.*
import java.util.*
@Controller
@RestController
@RequestMapping("/user")
class UserController {
@GetMapping()
fun getUser(@RequestParam(required = false) name: Optional<String>): String {
return "Hello ${name.orElse("World")}"
}
}
Query Parameter가 안들어 올 수 있다는 생각을 했고, 그럼에도 잘 동작하게 하고 싶어 옵션을 주고싶었다.
이전에 Java기반의 Spring과는 다르게 (required=false) 로만 옵션을 준 것이 아니라, 파라미터 변수의 자료형에 Optional<T> 를 주었다.
변수(query parameter) 가 들어온다면 들어온 것을 보여주고, 아니라면 World 를 출력하도록 return 값을 만들어서 각각의 상황에 대응하도록 만들었다.

테스트니까, GetMapping에서 인사를 해보자 - PathVariable
Query Parameter 말고도, url path에 변수를 주는 방법도 체크 해 보자.
url들은 http://www.abcd.com/user/1 맨 뒤의 1과 같이, 나타내고자 하는 resource의 가변적인 변수를 주기도 한다. GET 요청에서 뿐 아니라 많은 곳에서 사용 할 수 있기에 한번 간단히 사용해봤다.
@GetMapping("/{idx}")
fun getUserDetail(@PathVariable("idx") idx:Int):String{
return "Hello User Detail $idx"
}
아까와 같은 컨트롤러 내부에서 작성을 했고, idx라는 변수를 PathParam으로 잡았다. 이 변수를 받아주는 어노테이션은 @PathVarable이고, 저장 했던 변수 이름을 그대로 사용하면 된다.

Next Todo
다음 포스트에서는 POST 와 관련된 친구들을 간단히 살펴보고, Return 객체를 잘 설정 해 봐야겠다. 그리고 이어서 간단한 느낌을 잡았으니 이제 사용자 정보와 관련된 기능들을 개발 해 봐야겠다
- 사용자 테이블만들기
- 사용자 CRUD
- 로그인
I’m going to try developing Spring Boot using Kotlin.
I was a bit bored (?) and thought, let’s do another development project with Spring! And since I was making it anyway, I decided to try it with Kotlin.
It might be a bit disorganized, but I’ll organize what I look up while developing.
Spring Boot and Kotlin
I won’t write about setup since many people have already written about it. (Everyone has already done a great job explaining it)
I’m planning to create a project similar to LinkedIn. It’s a demo project, but I want to experience connecting many people.
Writing a Controller in Kotlin
I first wrote a controller related to User.

Within the package containing the base Application.kt, I set up a Controller package and created a Kotlin file below it.
Since it’s a test, let’s say hello with GetMapping - queryParam
While thinking about what to do with the controller, I thought let’s just do a simple test with GetMapping! I wanted to receive GET requests with GetMapping and wrote code to check incoming queryParams.
The annotation that receives query parameters is @RequestParam.
package com.example.linkwithbackend.controller
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.*
import java.util.*
@Controller
@RestController
@RequestMapping("/user")
class UserController {
@GetMapping()
fun getUser(@RequestParam(required = false) name: Optional<String>): String {
return "Hello ${name.orElse("World")}"
}
}
I thought the Query Parameter might not always come in, and I wanted it to work well anyway, so I wanted to give it options.
Unlike the previous Java-based Spring, I didn’t just give the option with (required=false), but also gave Optional<T> to the data type of the parameter variable.
I made the return value to show what came in if the variable (query parameter) comes in, and to output World otherwise, to handle each situation.

Since it’s a test, let’s say hello with GetMapping - PathVariable
Let’s also check the method of putting variables in the url path, not just Query Parameters.
URLs sometimes have variable parameters for the resource to be displayed, like the 1 at the end of http://www.abcd.com/user/1. Since it can be used in many places, not just GET requests, I tried it out briefly.
@GetMapping("/{idx}")
fun getUserDetail(@PathVariable("idx") idx:Int):String{
return "Hello User Detail $idx"
}
I wrote it inside the same controller as before, and set idx as the PathParam. The annotation that receives this variable is @PathVariable, and you just use the saved variable name as is.

Next Todo
In the next post, I’ll briefly look at POST-related things and try to properly set up the Return object. And now that I have a basic feel for it, I should develop features related to user information.
- Create user table
- User CRUD
- Login
댓글남기기