RequestMapping Annotation
GET
@RestController
class GreetingController {
@RequestMapping(value = [("/")], method = [RequestMethod.GET])
fun greeting(): String {
return "getMethod, Good to see you"
}
// 아래와 같이 변경 가능
@GetMapping("/")
fun greeting(): String {
return "getMethod, Good to see you"
}
@RequestMapping(value = ["/"], method = [RequestMethod.POST])
fun greetingUser(): String {
return "postMethod, Good to see you"
}
// 아래와 같이 변경 가능
@PostMapping("/")
fun greetingUser(): String {
return "postMethod, Good to see you"
}
}
파라미터 전달 (get)
@PathVariable
@GetMapping("/userNm/{userNm}")
fun greeting(@PathVariable userNm : String): String {
return "getMethod, Good to see you! userNm: $userNm"
}
@GetMapping("/userName/{userNm}")
// 변수명 변경하기 위해서 사용
fun greeting1(@PathVariable("userNm") userName : String): String {
return "getMethod, Good to see you! userName: $userName"
}
url query문
@GetRequestParam
url ?name=paramNm&email=testEmail
@GetMapping("/userNm")
fun greeting2(@RequestParam name: String, @RequestParam email: String): String {
return "getMethod, Good to see you! userName: \"$name\" :: email : \"$email\""
}
결과물 : getMethod, Good to see you! userName: "paramNm" :: email : "testEmail"
Map : 변수명이 정의 되지 않은 케이스
// Map 형식으로 받음
@GetMapping("/map")
fun greeting3(@RequestParam param: Map<String, String>): String {
val sb = StringBuilder()
param.entries.forEach { map ->
sb.append( "${map.key} = ${map.value}, " )
}
return "getMethod, Good to see you! userName: \"$sb\""
}
결과물: getMethod, Good to see you! userName: "name = paramNm, email = testEmail, "
DTO 사용
// DTO 사용
@GetMapping("/dto")
fun greeting4(user: UserDTO): String {
return "getMethod, Good to see you! userName: \"${user.name}\" :: email : \"${user.email}\""
}
//DTO
data class UserDTO( val name : String , val email: String)