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

개발자되기 프로젝트

GET 본문

@RestController를 사용하여 @GetMapping 사용 방법 들 을 알아보자.

 

1. @GetMapping


import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

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

    @GetMapping("/hello")
    fun hello(): String{
        return "hello kotlin"
    }

}

다음과 같이 @RequestMapping을 사용할 수 도 있다.  -> 요즘 잘 안씀

메서드 제약을 주고 싶으면 method에 배열로 지정하면 됨.

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

    @GetMapping("/hello")
    fun hello(): String{
        return "hello kotlin"
    }
    
    @RequestMapping(method = [RequestMethod.GET] , path = ["/request-mapping"]) //http method에 관계없이.
    fun requestMapping(): String{
        return "request-mapping"
    }

}

 

2. @PathVariable


@GetMapping("/get-mapping/path-variable/{name}")
fun pathVariable(@PathVariable name: String): String{
    println(name)
    return name
}

 

 

3. PathVariable 변수명 다를 때


@Pathvariable의 value, name 옵션에 URI에 있는 변수 명 지정하면 됨.

@GetMapping("/get-mapping/path-variable2/{name}/{age}")
fun pathVariable2(@PathVariable(value = "name") _name: String, @PathVariable(name = "age") age: Int): String{
    val name = "kotlin"
    println("name: ${_name}, age: ${age}")
    return _name + " " + age
}

 

 

 

4. QueryParameter: @RequestParam


@GetMapping("/get-mapping/query-param")
fun queryParam(@RequestParam name: String, @RequestParam age: Int): String{
    println("name: ${name}, age: ${age}")
    return "$name $age"
}

 

 

5. QueryParameter: Object 


  • 여러 개의 query Parameter를 받을 경우 메서드에 하나하나 적기 불편함
  • 객체를 활용하여 여러개의 파라미터를 이름으로 매핑하여 객체로 받을 수 있음.
  • QueryParameter로 받을 model 정의
    • Data class : data model을 정의할 수 있다. 
      • 생성자, getter, Setter, canonical methods를 생성해줌.
      • 제약사항
      • 기본 생성자에는 최소 하나의 파라미터가 있어야 한다.
      • 기본 생성자의 파라미터는 val이나 var여야만 한다.
      • 데이터 클래스는 abstract, open, sealed, inner가 되면 안 된다.
data class UserRequest(
    var name: String? = null,
    var age: Int? = null,
    var email: String? = null,
    var address: String? = null
)
  • 사용하는 방법은 간단하다. 
@GetMapping("/get-mapping/query-param/object")
fun queryParamObject(userRequest: UserRequest): UserRequest{
    println(userRequest.toString())
    return userRequest
}

 

응답을 보면 content type이 JSON으로 적용되었다.

 

@RestController를 사용하면 객체를 return할 경우  json으로 content type이 적용된다.

만약 단순히 String을 return하면 view를 찾거나 없으면 text로 지정됨.

 

  • 어떻게 동작하지?

@RestController = @Controller  + @ReponseBody

@ResponseBody는 return 값을 http message body에 넣어줌.

 

HTTP 메시지 컨버터가 RETURN 타입에 따라 응답 데이터를 생성해 줌. 

객체로 변환하여 받는 것도 HTTP 메시지 컨버터가 해줌.

 

HTTP 메시지 컨버터

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

bsh-developer.tistory.com

 

  • 주의사항
    • query paramter에 " - " 이 들어간 경우는 객체로 매핑할 수 없음.
    •  kotling에서는 변수 명에 " - " 허용하지 않음.
    • @RequestParam(name = "") 으로 직접 지정해야 함.

 

 

 

6. Query Parameter : Map


@GetMapping("/get-mapping/query-param/map")
fun queryParamMap(@RequestParam map: Map<String, Any>): Map<String, Any> {
    println(map)
    return map
}

 

추가로 query parameter에 "-"있는 경우 위와 같이 @QueryParam으로 직접 지정해도 되지만

Map으로도 받을 수 있다.

@GetMapping("/get-mapping/query-param/map")
fun queryParamMap(@RequestParam map: Map<String, Any>): Map<String, Any> {
    println(map)
    val phoneNumber = map.get("phone-number")
    return map
}

 

 

7. 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
POST  (0) 2022.04.24
[인프런] Web 개론  (0) 2022.04.24
Comments