개발놀이터

스프링 HTTP요청 메시지 - JSON 본문

Spring/Spring

스프링 HTTP요청 메시지 - JSON

마늘냄새폴폴 2021. 8. 19. 10:36

*HTTP 요청메시지 - JSON

-InputStream으로 읽어오는 방식

@PostMapping("/request-body-json-v1")
    public void requestBodyJsonV1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletInputStream inputStream = request.getInputStream();
        String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);

        log.info("messageBody={}", messageBody);

        HelloData helloData = objectMapper.readValue(messageBody, HelloData.class);

        log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());

        response.getWriter().write("ok");
    }


-@RequestBody로 읽어오는 방식

@ResponseBody
    @PostMapping("/request-body-json-v2")
    public String requestBodyJsonV2(@RequestBody String messageBody) throws ServletException, IOException {
        log.info("messageBody={}", messageBody);

        HelloData helloData = objectMapper.readValue(messageBody, HelloData.class);

        log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());

        return "ok";
    }


-@RequestBody로 읽어오는데 객체를 파라미터로 받으면 더 간단하게 바꿀 수 있다.

@ResponseBody
    @PostMapping("/request-body-json-v3")
    public String requestBodyJsonV3(@RequestBody HelloData helloData) throws ServletException, IOException {
        log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());

        return "ok";
    }


*@RequestBody 객체 파라미터
-@RequestBody HelloData helloData 이런식으로 객체를 파라미터로 받을 수 있다.
-@RequestBody에 직접 만든 객체를 지정할 수 있다.

HttpEntity, @RequestBody를 사용하면 HTTP 메시지 컨버터가 HTTP 메시지 바디의 내용을 우리가 원하는 문자나 객체 등으로 변환해준다. HTTP메시지 컨버터는 문자 뿐만 아니라 JSON객체로 변환해주는데, 우리가 방금 V2에서 했던 작업을 대신 처리해준다.

물론 HttpEntity로 꺼내올 수도 있다. 헤더에 관한 정보가 필요하면 HttpEntity가 필요하다.

@ResponseBody
    @PostMapping("/request-body-json-v4")
    public String requestBodyJsonV4(HttpEntity<HelloData> httpEntity) throws ServletException, IOException {
        HelloData helloData = httpEntity.getBody();
        log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());

        return "ok";
    }


리턴 타입을 HelloData로 하면 요청도 JSON으로 오고 응답도 JSON으로 간다

@ResponseBody
    @PostMapping("/request-body-json-v5")
    public HelloData requestBodyJsonV5(@RequestBody HelloData helloData) throws ServletException, IOException {
        log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());

        return helloData;
    }


응답의 경우에도 @ResponseBody를 사용하면 해당 객체를 HTTP메시지 바디에 직접 넣어줄 수 있다. 물론 이 경우에도 HttpEntity를 사용해도 된다.

@RequestBody 요청
-JSON 요청 -> HTTP 메시지 컨버터 -> 객체

@ResponseBody 응답
-객체 -> HTTP 메시지 컨버터 -> JSON 응답