HTTP 요청 메시지를 통한 데이터 전달 방법

 

GET
  • /url ? username = hello & age = 20
  • 메시지 바디 없이 URL 의 쿼리 피라미터에 데이터를 포함해서 전달
  • ex. 검색, 필터, 페이징 등에서 많이 사용하는 방식

[ 소스 코드 ]

 

package servletTest.servlet.request;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.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("단일 파라미터 조회 - start");
        String username = request.getParameter("username");
        String age = request.getParameter("age");

        System.out.println("username = " + username);
        System.out.println("age = " + age);
        System.out.println();
        System.out.println("단일 파라미터 조회 - end");

        System.out.println("중복되는 복수 파라미터 조회");
        String[] usernames = request.getParameterValues("username");
        for (String i : usernames) {
            System.out.println("username = " + i);
        }

    }
}

* 여기서 주의할 점은 복수 파리미터에 대한 부분입니다.

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

와 같은 url 로 username 을 중복해서 부르게 된다면 그 값이 없어지는게 아니라,

username 안에 두 값을 받아오게 됩니다.

 

그래서 값들을 담는 배열 객체를 만들어 저장 후 출력이 가능합니다.

 

 

 

 

POST
  • content-type : application / x-www.form-urlencoded
  • 메시지 바디에 쿼리 피라미터 형식으로 전달 username = hello & age = 20 ( url 형태와 비슷함 )
  • ex. 회원 가입, 상품 주문, HTML form 사용

 

1) POST 를 사용하려면 HTML Form이 필요합니다.

- webapp/basic 경로에 hello-form.html 을 생성해줍니다.

- http://localhost:8080/basic/hello-form.html 로 브라우저 접속

 

[ 폼 형태 ]

<form action="/request-param" method="post">
    username: <input type="text" name="username" />
    age: <input type="text" name="age" /> <button type="submit"> 전송 </button>
</form>

위의 폼을 보면 다음을 알 수 있습니다.

Form 전송을 누르게 되면 이전에 서블릿 경로로 만들어놨던 "/request-param" 경로로 전송하게 됩니다.

개발자도구를 켜서 폼 데이터를 보면 데이터가 제대로 들어왔음을 확인할 수 있습니다.

 

 

2) 위 데이터를 컨텐트 바디에 보내게 됩니다.

다음과 같이 엔코딩되어 전송 됩니다.

 

 

3) 데이터 확인

데이터가 정상적으로 출력되고 있음이 확인가능합니다.

 

 

 

 

[ 중간 정리 ]

1) request.getParameter 형식은 GET / POST 둘 다 지원한다.

2) POST 는 브라우저가 알아서 형식을 만들어서 전송한다.

3) GET 은 사용자가 Url 을 입력한다.

4) 즉, 클라이언트 입장에선 다르게 작성하지만

          서버입장에선 GET/POST 구분없이 조회가 가능합니다.

 

Q. 그럼 위와 같은 HTTP 메서드 테스트를 할 때, 매번 Html 파일을 만들어야 하는가?

A. 아니다. Postman 을 활용하자 !!

위의 과정을 Postman 을 통해 테스트한 결과, 200 OK가 나오면 정상 작동하는 것입니다.

 

 

HTTP message body 에 데이터 직접 담아서 요청
  • HTTP API 에서 주로 사용
  • JSON, XML, TEXT
  • 데이터 형식은 주로 JSON 사용
  • POST, PUT, PATCH

[ 소스 코드 ]

@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);// StreamUtils 를 통해 인코딩 정보를 알려주고 바이트 코드로 변환 시켜줌

        System.out.println("messageBody : " + messageBody);
        response.getWriter().write("ok");
    }
}

[ Postman Test ]

정상적으로 출력됨을 볼 수 있습니다.

'HTTP' 카테고리의 다른 글

HttpServletResponse 사용해보기  (0) 2022.11.26
JSON 형식으로 받은 데이터를 객체로 변환하기  (0) 2022.11.26
DTO  (0) 2022.08.22
RestAPI 활용하기  (0) 2022.08.22
Message States Server  (0) 2022.08.19

+ Recent posts