-
[스프링MVC - 1편] HTTP 요청 데이터스프링&스프링부트 2025. 1. 2. 20:08
HTTP 요청 데이터 개요
HTTP 요청 메세지를 통해 클라이언트에서 서버로 데이터를 전달하는 방법 3가지
- GET - 쿼리 파라미터
- /url**?username=hello&age=20**
- 메시지 바디 없이, URL의 쿼리 파라미터에 데이터를 포함해서 전달
- 예) 검색, 필터, 페이징등에서 많이 사용하는 방식
- POST - HTML Form
- content-type: application/x-www-form-urlencoded
- 메시지 바디에 쿼리 파리미터 형식으로 전달 username=hello&age=20
- 예) 회원 가입, 상품 주문, HTML Form 사용
- HTTP message body에 데이터를 직접 담아서 요청
- HTTP API에서 주로 사용, JSON, XML, TEXT
- 데이터 형식은 주로 JSON 사용
- POST, PUT, PATCH
HTTP 요청 데이터 - GET 쿼리 파라미터
메세지 바디 없이, URL의 쿼리 파라미터를 사용해서 데이터를 전달
http://localhost:8080/request-param?username=hello&age=20
쿼리 파라미터는 ?를 시작으로 보낼 수 있고 추가 파라미터는 &로 구분한다
서버에서는 HttpServletRequest가 제공하는 메서드를 통해 쿼리 파라미터를 편리하게 조회할 수 있다
@WebServlet(name="requestParamServlet", urlPatterns="/request-param") public class RequestParamServlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("[전체 파라미터 조회] - start"); request.getParameterNames().asIterator().forEachRemaining(paramName -> System.out.println(paramName + " = " + request.getParameter(paramName))); System.out.println("[전체 파라미터 조회] - end"); System.out.println(); System.out.println("[단일 파라미터 조회]"); String username = request.getParameter("username"); System.out.println("username = " + username); String age = request.getParameter("age"); System.out.println("age = " + age); System.out.println(); System.out.println("[이름이 같은 복수 파라미터 조회]"); String[] usernames = request.getParameterValues("username"); for (String name : usernames) { System.out.println("username = " + username); } } }
HTTP 요청 데이터 - POST HTML Form
content-type: application/x-www-form-urlencoded
메시지 바디에 쿼리 파리미터 형식으로 데이터를 전달 (username=hello&age=20)
// src/main/webapp/basic/hello-form.html 생성 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/request-param" method="post"> username: <input type="text" name="username" /> age: <input type="text" name="age" /> <button type="submit">전송</button> </form> </body> </html>
POST의 HTML Form을 전송하면 웹 브라우저는 다음 형식으로 HTTP 메시지를 만든다 (개발자도구 통해 확인 가능)
- 요청 URL: http://localhost:8080/request-param
- content-type: application/x-www-form-urlencoded
- message body: `username=hello&age=20
application/x-www-form-urlencoded 형식은 GET에서 살펴본 쿼리 파라미터 형식과 같다
따라서 쿼리 파라미터 조회 메서드를 그대로 사용하면 된다
클라이언트(웹 브라우저) 입장에서는 두 방식에 차이가 있지만,
서버 입장에서는 둘의 형식이 동일하므로 request.getParameter()로 편리하게구분 없이조회할 수 있다
정리하면 request.getParameter()는 GET URL 쿼리 파라미터 형식도 지원하고, POST HTML Form 형식도 지원한다
HTTP 요청 데이터 - API 메시지 바디
HTTP message body에 데이터를 직접 담아서 요청
- HTTP API에서 주로 사용 (JSON, XML, TEXT)
- 데이터 형식은 주로 JSON 사용
- POST, PUT, PATCH
1. 단순 텍스트
가장 단순한 텍스트 메시지를 HTTP 메시지 바디에 담아서 전송하고
HTTP 메시지 바디의 데이터를 InputStream을 사용해서 직접 읽을 수 있다
@WebServlet(name = "requestBodyStringServlet", urlPatterns = "/request-body-string") public class RequestBodyStringServlet extends HttpServlet{ @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletInputStream inputStream = request.getInputStream(); String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8); System.out.println("messageBody = " + messageBody); response.getWriter().write("ok"); } }
2. JSON
- POST http://localhost:8080/requeset-body-json
- content-type: application/json
- message body : {"username" : "hello", "age" : 20}
- 결과 : messageBody = {"username" : "hello", "age" : 20}
JSON 형식 파싱 추가
JSON 형식으로 파싱 할 수 있게 객체 추가 (보통 JSON은 그대로 사용하지 않고 객체로 바꿔서 사용한다)
@Getter @Setter public class HelloData { private String username; private int age; }
@WebServlet(name = "requestBodyJsonServlet", urlPatterns = "/request-body-json") public class RequestBodyJsonServlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletInputStream inputStream = request.getInputStream(); String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8); System.out.println("messageBody = " + messageBody); } }
content-type 자동 변경 JSON 라이브러리 - JACKSON 추가
@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 { 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.getUsername = " + helloData.getUsername()); System.out.println("helloData.getAge = " + helloData.getAge()); } }
728x90'스프링&스프링부트' 카테고리의 다른 글
[스프링MVC - 1편] 회원관리 웹 애플리케이션 구현 (0) 2025.01.05 [스프링MVC - 1편] HTTPServletResponse (1) 2025.01.05 [스프링MVC - 1편] HttpServletRequest (0) 2025.01.02 [스프링MVC - 1편] Hello 서블릿 (0) 2024.12.25 [intelliJ / springboot] 'Java/JavaVirtualMachines/openjdk-23.0.1/Contents/Home/bin/java' finished with non-zero exit value 1 (0) 2024.12.25 - GET - 쿼리 파라미터