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
GET 쿼리 파라미터
전달 데이터 : username=hello, age=20
메시지 바디 없이, URL의 "쿼리 파라미터"를 사용해서 데이터 전달해보기
http://localhost:8080/request-param?username=hello&age=20
RequestParamServlet.java
package hello.servlet.basic.request;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@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");
String age = request.getParameter("age"); //단축키 option+command+v
System.out.println("username = " + username);
System.out.println("age = " + age);
System.out.println();
System.out.println("[이름이 같은 복수 파라미터 조회]");
String[] usernames = request.getParameterValues("username");
for (String name: usernames) {
System.out.println("name = " + name);
}
response.getWriter().write("ok");
}
}
http://localhost:8080/request-param?username=hello&age=20&username=hello2 요청 시
POST HTML Form
content-type : 'application/x-www-form-urlencoded'
메시지 바디에 쿼리 파라미터 형식으로 데이터를 전달함
http://localhost:8080/basic/hello-form.html 실행해보기
- content-type : `application/x-www-form-urlencoded`
- message body : `username=hello&age=20`

정리하면 `request.getParameter()` 는 GET URL 쿼리 파라미터 형식도 지원하고, POST HTML Form 형식도 둘 다 지원한다.
Postman으로 테스트 가능
POST 전송시
- Body `x-www-form-urlencoded` 선택
- Headers에서 content-type: `application/x-www-form-urlencoded` 로 지정된 부분 꼭 확인

API 메시지 바디
단순 텍스트
HTTP message body에 데이터를 직접 담아서 요청
- HTTP API에서 주로 사용,
- JSON, XML, TEXT 데이터 형식은 주로 JSON 사용
- POST, PUT, PATCH

postman 확인 완료
JSON
JSON 형식 전송
POST http://localhost:8080/request-body-json
content-type: **application/json**
message body: `{"username": "hello", "age": 20}`
결과: `messageBody = {"username": "hello", "age": 20}`
package hello.servlet.basic;
import lombok.Getter;
import lombok.Setter;
//lombok 세팅했으면 이렇게 Getter, Setter 세팅 가능
@Getter
@Setter
public class HelloData {
private String username;
private int age;
}
RequstBodyJsonServlet.java
package hello.servlet.basic.request;
import com.fasterxml.jackson.databind.ObjectMapper;
import hello.servlet.basic.HelloData;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.StreamUtils;
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 {
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");
}
}
JSON 결과를 파싱해서 사용할 수 있는 자바 객체로 변환하려면 Jackson, Gson 같은 JSON 변환 라이브러리 를 추가해서 사용해야 한다.
스프링 부트로 Spring MVC를 선택하면 기본으로 Jackson 라이브러리 ( `ObjectMapper` )를 함께 제공한다.
'BackEnd : Spring > Spring MVC' 카테고리의 다른 글
[Spring MVC] FrontController 패턴 생성하기 (0) | 2024.04.06 |
---|---|
[Spring MVC] HttpServletResponse, Http 응답 데이터 (0) | 2024.03.23 |
[Spring MVC] HelloServlet, HttpServletRequest (0) | 2024.03.20 |
[Spring MVC] 자바 백엔드 웹 기술 역사 (1) | 2024.03.16 |
[Spring MVC] HTML, HTTP API, CSR, SSR (0) | 2024.03.16 |