Kotlin을 사용한 Spring Boot 개발기 - Controller (@RequestParam, @PathVariable) Spring Boot with Kotlin - Controller (@RequestParam, @PathVariable)
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
댓글남기기