HTTP API에서 사용하는 JSON 형식으로 데이터를 전달해보자.
JSON 형식 전송
- POST http://localhost:8080/request-body-json
- content-type: application/json
- message body: {"username": "hello", "age": 20}
- 결과: messageBody = {"username": "hello", "age": 20} 출력되게 만들어 보자.
HelloData Class를 만들어주고

lombok 라이브러리가 있으니까 getter setter을 직접 쓰는 대신에 어노테이션으로 넣어준다.
// basic - HelloData Class
package hello.setvlet.basic;
import lombok.Getter;
import lombok.Setter;
@Getter @Setter
public class HelloData {
private String username;
private int age;
}
RequestBodyJsonServlet를 request package 밑에다가 만들어준다.

실행 도중에 에러가 났는데
// RequestBodyJsonServlet class
package hello.setvlet.basic.request;
import org.springframework.util.StreamUtils;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@WebServlet(name = "RequestBodyJsonServlet", urlPatterns = "/request-body-json")
public class RequestBodyJsonServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// http message body에 있는 거를 가져와보자.
ServletInputStream inputStream = request.getInputStream();
String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
System.out.println("messageBody = " + messageBody);
}
}
이글과 댓글을 참고하여 build.gradle에 있는 starter-tomcat을 주석처리하여 에러해결
// providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
postman으로 데이터를 post 해보면
http://localhost:8080//request-body-json

결과가 잘 나오는 것을 확인할 수 있다.
messageBody = {"username": "hello", "age":20}
helloData로 바로 변환을 시켜보자.
package hello.setvlet.basic.request;
import com.fasterxml.jackson.databind.ObjectMapper;
import hello.setvlet.basic.HelloData;
import org.springframework.util.StreamUtils;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@WebServlet(name = "requestBodyJsonServlet", urlPatterns = "/request-body-json")
public class RequestBodyJsonServlet extends HttpServlet {
private ObjectMapper objectMapper = new ObjectMapper();
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// http message body에 있는 거를 가져와보자.
ServletInputStream inputStream = request.getInputStream();
String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
System.out.println("messageBody = " + messageBody);
HelloData helloData = objectMapper.readValue(messageBody, HelloData.class);
System.out.println("helloData.username = " + helloData.getUsername());
System.out.println("helloData.age = " + helloData.getAge());
response.getWriter().write("ok");
}
}
postman으로 객체로 변환된 결과를 잘 확인할 수 있다.
messageBody = {"username": "hello", "age":20}
helloData.username = hello
helloData.age = 20
결론적으로
- JSON 결과를 파싱해서 사용할 수 있는 자바 객체로 변환하려면 Jackson, Gson 같은 JSON 변환 라이브러리를 추가해서 사용해야 한다. 스프링 부트로 Spring MVC를 선택하면 기본으로 Jackson 라이브러리(ObjectMapper )를 함께 제공한다.
그리고
- HTML form 데이터도 메시지 바디를 통해 전송되므로 직접 읽을 수 있다. postman - x-www-form-urlencoded에서 보자.

message body에 있는 데이터를 그대로 뿌려준다. JSON 형식이 아니니까 파싱은 불가()

messageBody = username=kim&age=20
-
하지만 편리한 파리미터 조회 기능( request.getParameter(...) )을 이미 제공하기 때문에 파라미터 조회 기능을 사용하면 된다.
<출처 김영한: 스프링 MVC 1편 - 벡앤드 웹 개발 핵심 기술>
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-1/dashboard
스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 - 인프런 | 강의
웹 애플리케이션을 개발할 때 필요한 모든 웹 기술을 기초부터 이해하고, 완성할 수 있습니다. 스프링 MVC의 핵심 원리와 구조를 이해하고, 더 깊이있는 백엔드 개발자로 성장할 수 있습니다., -
www.inflearn.com
'Spring > SpringMVC' 카테고리의 다른 글
HTTP 응답 데이터 - 단순 텍스트, HTML / API JSON (0) | 2022.04.22 |
---|---|
HttpServletResponse - 기본 사용법 (0) | 2022.04.22 |
HTTP 요청 데이터 - API 메시지 바디 - 단순 텍스트 (0) | 2022.04.22 |
HTTP 요청 데이터 - POST HTML Form - 로그 에러 (0) | 2022.04.21 |
HTTP 요청 데이터 - GET 쿼리 파라미터 (0) | 2022.04.21 |