MVC 프레임워크 14

Mar 9, 2023

3 mins read

HTTP 요청 메시지 - JSON

  • 이번에는 HTTP API에서 주로 사용하는 JSON 데이터 형식을 조회해보자.
package hello.springmvc.basic.request;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;

import hello.springmvc.basic.HelloData;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
public class RequestBodyJson {

	private ObjectMapper objectMapper = new ObjectMapper();
	
	/*
	 * HttpServletRequest를 사용해서 직접 HTTP 메시지 바디에서 데이터를 읽어와서, 문자로 변환한다.
	 * 문자로 된 JSON 데이터를 Jackson 라이브러리인 objectMapper 를 사용해서 자바 객체로 변환한다.
	 */
	@RequestMapping("/request-body-json-v1")
	public void requestBodyJsonV1(HttpServletRequest request, HttpServletResponse response) throws 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
	 * HttpMessageConverter 사용 -> StringHttpMessageConverter 적용
	 *
	 * @ResponseBody
	 * - 모든 메서드에 @ResponseBody 적용
	 * - 메시지 바디 정보 직접 반환(view 조회X)
	 * - HttpMessageConverter 사용 -> StringHttpMessageConverter 적용
	 */
	@ResponseBody
	@RequestMapping("/request-body-json-v2")
	public String requestBodyJsonV2(@RequestBody String messageBody) throws IOException {
		log.info("messageBody={}", messageBody);
		HelloData helloData = objectMapper.readValue(messageBody, HelloData.class);
		log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
		return "ok";
	}
	
	/*
	 * @RequestBody 생략 불가능(@ModelAttribute 가 적용되어 버림, HTTP 메시지 바디가 아니라 요청 파라미터를 처리하게 된다)
	 * HttpMessageConverter 사용 -> MappingJackson2HttpMessageConverter (contenttype: application/json)
	 *
	 */
	@ResponseBody
	@RequestMapping("/request-body-json-v3")
	public String requestBodyJsonV3(@RequestBody HelloData data) throws IOException {
		log.info("username={}, age={}", data.getUsername(), data.getAge());
		return "ok";
	}
	
	/*HttpEntity도 사용 가능*/
	@ResponseBody
	@RequestMapping("/request-body-json-v4")
	public String requestBodyJsonV4(HttpEntity<HelloData> httpEndtity) throws IOException {
		HelloData data = httpEndtity.getBody();
		log.info("username={}, age={}", data.getUsername(), data.getAge());
		return "ok";
	}
	

	/*
	 * 응답의 경우에도 @ResponseBody 를 사용하면 해당 객체를 HTTP 메시지 바디에 직접 넣어줄 수 있다.
	 * @RequestBody 요청 : JSON 요청->HTTP 메시지 컨버터->객체
	 * @ResponseBody 응답 : 객체->HTTP 메시지 컨버터->JSON 응답
	 */
	@ResponseBody
	@RequestMapping("/request-body-json-v5")
	public HelloData requestBodyJsonV5(@RequestBody HelloData data) throws IOException {
		log.info("username={}, age={}", data.getUsername(), data.getAge());
		return data;
	}
	
}
  • postman으로 확인한 request-body-json-v5 JSON요청, JSON응답

request_body_json