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

개발자되기 프로젝트

ResponseEntity, @ResponseBody 본문

인프런/[인프런] Kotlin으로 개발하는 Spring Boot Web MVC

ResponseEntity, @ResponseBody

Seung__ 2022. 4. 24. 22:42
 

RequestMapping Handler Adapter 구조

HTTP 메시지 컨버터는 SpringMVC 어디 쯤? 에서 사용됨....? 1. SpringMVC 구조 @RequestMapping을 처리하는 핸들러 Adapter인 RequestMappingHandlerAdapter에서 처리함. 2. RequestMappingHandlerAdapter 동작..

bsh-developer.tistory.com

 

HTTP 요청 메시지 - 단순 텍스트

1.HTTP message Body에 데이터를 직접 담아서 요청할 수 있음. HTTP API에서 주로 사용, JSON, XML, TEXT JSON 형식 POST, PUT, PATCH 요청 파라미터와 다르게 HTTP 메시지 바디에 데이터를 답아서 넘어오..

bsh-developer.tistory.com

 

HTTP response - HTTP API, 메시지 바디에 직접 입력

https://github.com/bsh6463/MVC2HTTP API를 제공하는 경우 데이터를 전달해야함. 따라서 Message Body JSON형식으로 전달해야함. 1. HttpServletResponse 사용 writer를 가져와서 data를 message body에 넣음. @G..

bsh-developer.tistory.com

String 일반 text type 응답
Object RestController 사용 시 응답 메세지 바디에 JSON으로
변환되어 응답. 항상 200 ok 
ResponseEntity Body의 내용을 Object로 설정
상황에 따라 HttpStatus Code 설정
@ResponseBody RestController가 아닌 곳(Controller)에서 Json응답 내릴 때

 

1. ResponseEntity


package com.example.kotlinspring.controller.response

import com.example.kotlinspring.model.UserRequest
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/api/response")
class ResponseApiController {

    //1. get, 4xx
    @GetMapping()
    fun getMapping(@RequestParam age:Int?): ResponseEntity<String>? {

        return age?.let {
            //age != null
            if(it < 20){
                return ResponseEntity.badRequest().body("age 값은 20이상이어야 합니다.")
            }

            ResponseEntity.ok("ok")
        }?: kotlin.run {
            //age == null
            return ResponseEntity.status(400).body("age값이 누락되었습니다.")
        }


        /*
        //required = 필수 값 옵션, default: trie
        //1. age == null -> 400
        if(age == null){
            //return ResponseEntity.badRequest().body("fail")
            return ResponseEntity.status(400).body("age값이 누락되었습니다.")
        }

        //2. age < 20 -> 400
        if (age < 20){
            return ResponseEntity.badRequest().body("age 값은 20이상이어야 합니다.")
        }

        return ResponseEntity.ok("ok")
        */
    }

    //2. post, 200
    @PostMapping
    fun postMapping(@RequestBody userRequest: UserRequest?): ResponseEntity<Any>? {
        return ResponseEntity.status(200).body(userRequest) //body 비어있음.
    }

    //3. put, 201
    @PutMapping
    fun putMapping(@RequestBody userRequest: UserRequest?): ResponseEntity<UserRequest> {
        //기존 데이터가 없어서 새로 생성
        return ResponseEntity.status(HttpStatus.CREATED).body(userRequest)
    }

    //4. delete, 500
    @DeleteMapping("/{id}")
    fun deleteMapping(@PathVariable id: Int): ResponseEntity<Any> {
        return ResponseEntity.status(500).body(null)
    }
}

 

 

2. @Response


  • @Controller
    - return 이 String인 경우 해당 이름을 가진 view를 찾아감.(resource-static 하위에서 찾음)
@Controller
class PageController {

    @GetMapping("/main")
    fun main(): String {
        println("init main")
        return "main.html"
    }
}
  • main.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>Kotlin Spring boot</h1>

</body>
</html>
  • Thymeleaf를 사용할 경우 templates에서 찾음.

  • @Controller를 사용하는데 view를 찾는 것이 아니라 메세지 body에 데이터를 넣고 싶다?
    --> @ResponseBody
@ResponseBody
@GetMapping("/test")
fun response(): String {
    return "main.html"
}

위와 같이 String을 응답으로 하는경우 String이 메세지 바디에 담겨서 응답.

  • @ResponseBody, 객체 반환하는 경우 --> JSON형태로 응답.
@ResponseBody
@GetMapping("/test")
fun response(): UserRequest {
    return UserRequest().apply { 
        this.name = "Aaa"
    }
}

 

3. GitHub


 

GitHub - bsh6463/KotlinSpring: GET

GET. Contribute to bsh6463/KotlinSpring development by creating an account on GitHub.

github.com

 

'인프런 > [인프런] Kotlin으로 개발하는 Spring Boot Web MVC' 카테고리의 다른 글

JSR-380 Bean Validation : custom annotaion  (0) 2022.04.25
JSR-380 Bean Validation  (0) 2022.04.24
DELETE  (0) 2022.04.24
PUT, Request Body, ResponseBody  (0) 2022.04.24
POST  (0) 2022.04.24
Comments