[스프링 MVC 1편] - 서블릿 HttpServletRequest(http요청데이터)

2023. 1. 2. 17:35·Spring

HTTP 요청 데이터

대표적으로 3가지 방법

GET - 쿼리 파라미터

  • /url?username=hello&age=20
  • url의 쿼리 파라미터에 데이터를 포함해서 전달
  • ex ) 검색 , 필터 , 페이징에서 많이 사용

POST - HTML form

  • html form을 이용하여 전달
  • 메시지 바디에 쿼리 파라미터 형식으로 전달(username=hello&age=20)
  • content-type: application/x-www-form-urlencoded

HTTP message body에 담아서 전달

  • HTTP API에서 주로 사용(JSON 이용)
  • POST , PUT , PATCH
  • GET 쿼리 파라미터
  • http://localhost:8080/request-param?username=hello&age=20 와 같이 url을 통해 데이터 전달
String username = request.getParameter("username"); //단일 파라미터 조회
Enumeration<String> parameterNames = request.getParameterNames(); //파라미터 이름들 모두 조회
Map<String, String[]> parameterMap = request.getParameterMap(); //파라미터를 Map으로 조회
String[] usernames = request.getParameterValues("username"); //복수 파라미터 조회

POST HTML Form

  • content-type: application/x-www-form-urlencoded
  • 메시지 바디에 쿼리 파리미터 형식으로 데이터를 전달한다. username=hello&age=20
  • form으로 데이터를 전송하지만 서버입장에서는 쿼리 파라미터를 받기 때문에 위와 같이 request.getParameter()으로 편리하게 조회
  • request.getParameter() 는 GET URL 쿼리 파라미터 형식도 지원하고, POST HTML Form 형식도 둘 다 지원한다

API 메시지 바디 - 단순 텍스트

  • HTTP message body에 데이터를 직접 담아서 요청
  • text메시지를 http메서드 바디에 담아 전송
  • inputStream은 byte 코드를 반환한다. byte 코드를 우리가 읽을 수 있는 문자(String)로 보려면 문자표 (Charset)를 지정해주어야 한다. 여기서는 UTF_8 Charset을 지정해주었다.
@WebServlet(name = "requestBodyStringServlet", urlPatterns = "/request-bodystring")
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);
    }
}

JSON

  • JSON은 보통 객체를 따로 만들어 관리
@Getter @Setter
public class HelloData {
    private String username;
    private int age;
}
  • JSON 결과를 파싱해서 객체로 변환하기 위해서는 Jackson, Gson 같은 JSON변환 라이브러리를 추가사용해야한다.
  • 스프링부트로 Spring MVC를 선택하면 기본적으로 Jackson라이브러리(ObjectMapper)를 함께 제공한다.
@WebServlet(name = "requestBodyJsonServlet", urlPatterns = "/request-bodyjson")
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);
        HelloData helloData = objectMapper.readValue(messageBody, HelloData.class);
    }
}

참고 강의

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-1/dashboard

728x90
저작자표시 (새창열림)

'Spring' 카테고리의 다른 글

[spring] @PostConstruct 와 @PreDestroy 어노테이션  (1) 2023.01.05
[스프링 MVC 1편] - HttpServletResponse  (0) 2023.01.03
[스프링 MVC 1편] - 서블릿 HttpServletRequest(startLine, header)  (0) 2023.01.02
[스프링 MVC 1편] - 서블릿  (0) 2023.01.02
[스프링 MVC 1편] - 웹 애플리케이션 이해  (1) 2022.12.31
'Spring' 카테고리의 다른 글
  • [spring] @PostConstruct 와 @PreDestroy 어노테이션
  • [스프링 MVC 1편] - HttpServletResponse
  • [스프링 MVC 1편] - 서블릿 HttpServletRequest(startLine, header)
  • [스프링 MVC 1편] - 서블릿
study ticket
study ticket
  • study ticket
    혼자하는 공부
    study ticket
  • 전체
    오늘
    어제
    • 개발 (77)
      • 오류 (1)
      • Spring (13)
      • Java (0)
      • Data structure (6)
      • Algorithm (49)
        • 백준 (17)
        • 프로그래머스 (2)
      • 문제풀면서 알게되는것들 끄적 (2)
      • 머신러닝 (4)
        • sklearn (3)
        • pandas (1)
      • 프로젝트 (0)
        • 핏두 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    백준1157
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
study ticket
[스프링 MVC 1편] - 서블릿 HttpServletRequest(http요청데이터)
상단으로

티스토리툴바