쌓고 쌓다

HTTP 요청 데이터 본문

프로그래밍/JSP & Servlet

HTTP 요청 데이터

승민아 2023. 7. 20. 15:35

HTTP 요청 데이터

HTTP 요청 메시지를 통해 클라이언트에서 서버로 데이터를 전달하는 3가지 방식이 있다.

  • GET - 쿼리 파라미터
    • /url?username=LSM&age=1
    • 메시지 바디 없이, 쿼리 파라미터에 데이터를 담아 전달
  • POST - HTML Form
    • content-type: application/x-www-form-urlencoded
    • 메시지 바디에 쿼리 파라미터 형식으로 전달
  • HTTP message Body에 직접 데이터를 담아서 요청
    • HTTP API에서 주로 사용 (JSON, TEXT)
    • JSON 주로 사용하며 POST, PUT, PATCH

 

1.  GET 쿼리 파라미터

username=LEE, age=1 데이터를 아래의 URL로 전달한다.

http://localhost:8080/request-param?username=hello&age=20

쿼리 파라미터는 ?를 시작으로 보내며 구분자는 &이다.

 

파라미터 조회 방법

// 단일 파라미터 조회 - 여러 파라미터 존재시 첫번째만 반환
String username = request.getParameter("username"); 

// 전체 파라미터 조회
request.getParameterNames().asIterator()
	.forEachRemaining(param -> System.out.println(param + " : " + request.getParameter(param)));

// 이름이 같은 복수 파라미터 조회 - username=LEE&age=1&username=LSM
String[] parameterValues = request.getParameterValues("username");
for (String parameterValue : parameterValues) {
	System.out.println("parameterValue = " + parameterValue);
}

 

2.  POST HTML Form

HTML Form 전송 (출처: 인프런-김영한)

아래의 특징을 기억하자.

  • content-type: application/x-www-form-urlencoded
  • 메시지 바디에 쿼리 파리미터 형식으로 데이터를 전달한다.
    • 서버 입장에서 형식이 동일하여 쿼리 파라미터 조회 메서드 사용 가능

 

content-type은 HTTP 메시지 바디의 데이터 형식을 지정한다.
GET URL 쿼리 파라미터 형식은 HTTP 메시지 바디를 사용하지 않기 때문에 content-type이 존재하지 않는다.
POST HTML Form 형식은 HTTP 메시지 바디에 데이터를 포함해서 보내기 때문에
바디에 어떤 데이터 형식인지 content-type을 지정해줘야 한다.
폼으로 데이터를 전달하는 형식을 application/x-www-form-urlencoded이라고 한다.

 

3.  HTTP message body

HTTP 메시지 바디의 데이터를 InputStream을 사용해서 직접 읽을 수 있다.

 

3.1 API 메시지 바디 - 텍스트

단순 텍스트 메시지를 HTTP 메시지 바디에 담아서 전송과 읽기를 해보자.

ServletInputStream inputStream = request.getInputStream();
String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
System.out.println("messageBody = " + messageBody);

전송

  • POST http://localhost:8080/request-body-string
  • content-type: text/plain
  • message body: hello

출력

  • messageBody = hello

3.2 API 메시지 바디 - 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 {

    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());
    }
}

전송

  • POST http://localhost:8080/request-body-json
  • content-type: application/json
  • message body: {"username": "LSM", "age": 1}

출력

  • messageBody = {"username":"LSM", "age": 2}
  • helloData UserName = LSM
  • helloData Age = 2

 

JSON 결과를 파싱해서 자바 객체로 변환하려면 Jackson 같은 JSON 변환 라이브러리가 필요하다.

 

 

 

 

'프로그래밍 > JSP & Servlet' 카테고리의 다른 글

서블릿, JSP로 MVC 패턴 만들기  (0) 2023.07.29
JSP 애플리케이션과 MVC 패턴  (0) 2023.07.25
서블릿 애플리케이션과 템플릿 엔진  (0) 2023.07.24
HTTP 응답 데이터  (0) 2023.07.22
서블릿  (0) 2023.07.19
Comments