티스토리 뷰

해당 글은 김영한님의 스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 - 인프런 | 강의를 수강하고 정리한 게시글입니다.

HTTP 요청데이터

GET 방식의 HTTP 요청 메시지

HTTP 요청 메시지를 확인할 때 서블릿([Spring MVC] 02. 서블릿(Servlet)) 을 이용하면 보다 쉽게(자동화) HTTP 요청 메시지, HTTP 응답 메시지를 처리할 수 있다. 이는 서블릿이 HttpServletRequestHttpServletResponse를 제공하기 때문이다.

 

[HttpServletRequest 역할]
HTTP 요청 메시지를 개발자가 직접 파싱해서 사용해도 되지만, 매우 불편할 것이다.서블릿은 개발자가 HTTP 요청 메시지를 편리하게 사용할 수 있도록 개발자 대신에 HTTP 요청 메시지를 파싱한다. 그리고 그 결과를 HttpServletRequest 객체에 담아서 제공한다.

 

HttpServletRequest를 사용하면 다음과 같은 HTTP 요청 메시지를 편리하게 조회할 수 있다.

 

참고:
HttpServletRequest, HttpServletResponse를 사용할 때 가장 중요한 점은 이 객체들이 HTTP 요청 메시지, HTTP 응답 메시지를 편리하게 사용하도록 도와주는 객체라는 점이다. 따라서 이 기능에 대해서 깊이있는 이해를 하려면 HTTP 스펙이 제공하는 요청, 응답 메시지 자체를 이해해야 한다.
[Network] 04. HTTP 메시지[Spring MVC] 05. 서블릿 실습 환경 설정

 

이제 HttpServletRequest를 통해 HTTP 요청 메시지를 클라이언트에서 서버로 데이터를 전달하는 방법을 알아보자.

 

데이터를 전달할 때는 주로 다음 3가지 방법을 사용한다.

 

1. GET - 쿼리 파라미터

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

 

2. POST - HTML Form

  • HTML Form을 사용해서 메시지 바디에 쿼리 파리미터 형식으로 전달하는 방식
  • 회원 가입, 상품 주문등에 사용

 

3.HTTP message body에 데이터를 직접 담아서 전송

  • HTTP API에서 주로 사용하는 방식
  • 데이터 형식은 주로 JSON으로 사용한다.

 

GET 쿼리 파라미터

GET 쿼리 파라미터를 통해 요청 메시지를 보내고 이를 어떻게 확인하는지 연습해보자.

 

GET 쿼리 파라미터는 URL에서 ‘?’를 통해 key=value 꼴로 값을 집어넣으면 되고 여러개의 쿼리 파라미터가 필요한 경우 ‘&’를 사용해 주면 된다.

서블릿을 통해 서버에서 요청 데이터를 확인해보자.


/**
 * 1. 파라미터 전송 기능
 * http://localhost:8080/request-param?username=hello&age=20
 */
@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("name = " + name);
        }

        response.getWriter().write("ok");
    }
}

오버라이드한 service 메서드에서 request(HttpServletRequest) 인자를 통해 전체 파라미터 조회, 단일 파라미터 조회를 확인할 수 있다.

 

POST HTML FORM


HTML FORM를 사용해서 서버에 전송할 수 있지만 이런 간단한 데이터 전송은 귀찮게HTML FORM을 만들지 않고 Postman을 사용해서 테스트 해볼 수 있다.

 

이때, Postman에서 Body 에 x-www-form-urlencoded 를 선택해주고 값을 넣어 URL에 전송해주면 ‘GET 방식’과 같이 요청데이터를 확인할 수 있다.

참고 :
HTML FORM 방식은 GET방식과 같기 때문에 GET 방식에서 사용한 코드를 이용하면 된다. 즉, http://localhost:8080/request-param URL에 Key, Value 형식을 이용해보내고 GET 방식 코드를 그대로 이용해서 확인하면 된다.

 

API 메시지 바디

API 메시지 바디 방식은 HTTP message body에 데이터를 넣어 전송하는 방식으로 ServletInputStream를 통해 입력을 읽고 StreamUtils로 스트링으로 변환해주면 된다.

 

추가로 JSON 방식은 단지 Jackson같은 JSON 변환 라이브러리를 이용해 클래스등으로 변환만 해주면 된다.

 

요청 데이터를 보낼때는 HTML FORM과 같은 Postman을 이용하여 전달하였다

참고:
Postman에서 Body에 raw를 선택하고 JSON형식으로 보내주면 된다.

 

단순 텍스트

@WebServlet(name = "requestBodyStringServlet", urlPatterns = "/request-body-string")
public class RequestBodyStringServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletInputStream inputStream = req.getInputStream();
        String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);

        System.out.println("messageBody = " + messageBody);

        resp.getWriter().write("ok");
    }
}

단순 텍스트 형식의 경우 입력을 StreamUtils로 String 형식으로 바꿔주기만 하면 messageBody를 확인할 수 있다.

 

JSON

@WebServlet(name = "requestBodyJsonServlet", urlPatterns = "/request-body-json")
public class RequestBodyJsonServlet extends HttpServlet {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletInputStream inputStream = req.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());

        resp.getWriter().write("ok!");
    }
}

JSON 방식은 단순 텍스트 형식과 동일한 과정을 거치고 ObjectMapper로 원하는 클래스로 변형시켜 요청 데이터를 활용할 수 있다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함