728x90
import com.fasterxml.jackson.databind.ObjectMapper;
import hello.springmvc.basic.HelloData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@Slf4j
@Controller
public class RequestBodyJsonController {
private ObjectMapper objectMapper = new ObjectMapper();
@PostMapping("/request-body-sjon-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("helloData = {}",helloData);
response.getWriter().write("OK");
}
@ResponseBody
@PostMapping("/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("helloData = {}",helloData);
return "ok";
}
@ResponseBody
@PostMapping("/request-body-json-v3")
//@RequestBody 생략 불가능 생략하면 @ModelAttribute가 적용된다
public String requestBodyJsonV3(@RequestBody HelloData helloData) throws IOException {
log.info("helloData = {}",helloData);
return "ok";
}
@ResponseBody
@PostMapping("/request-body-json-v4")
public String requestBodyJsonV4(HttpEntity<HelloData> httpEntity) throws IOException {
HelloData helloData = httpEntity.getBody();
log.info("helloData = {}",helloData);
return "ok";
}
@ResponseBody
@PostMapping("/request-body-json-v5")
// 객체가 json으로 바껴서 응답한다
public HelloData requestBodyJsonV5(@RequestBody HelloData helloData) throws IOException {
log.info("helloData = {}",helloData);
return helloData;
}
}
728x90
'백엔드 > Spring(Boot)' 카테고리의 다른 글
스프링 HTTP 응답 (HTTP API, 메시지 바디에 직접 입력) (0) | 2021.09.10 |
---|---|
스프링 정적 리소스, 뷰 템플릿 (0) | 2021.09.10 |
HTTP 요청 메시지 (단순 텍스트) (0) | 2021.09.09 |
스프링 HTTP 요청 파라미터 - @ModelAttribute (0) | 2021.09.09 |
스프링 HTTP 요청 파라미터 - @RequestParam (0) | 2021.09.09 |