[Spring] HTTP 요청 데이터 전달 방법

hi·2022년 9월 12일
0

클라이언트 -> 서버로 요청 데이터를 전달하는 세가지 방법

① 쿼리 파라미터 (GET)
② HTML Form (POST)
③ HTTP 메시지 바디


①+② 쿼리 파라미터 전송

1) request.getParameter()

  • HttpServletRequest 제공 방식

2) @RequestParam

public String requestParam (@RequestParam("username") String memberName)
  • 파라미터 이름으로 바인딩
  • 파라미터명과 변수명 같을 경우 ("username") 생략 가능
  • Strung, int 등 단순 타입일 경우 @RequestParam 생략 가능

3) @ModelAttribute

  • 객체를 생성하고 값을 넣는 과정을 자동화
  • 생략 가능

🔎 @RequestParam vs @ModelAttribute

String, int 같은 단순 타입 : @RequestParam
그 외(argument resolver로 지정된 타입 외) : @ModelAttribute

③ 메시지 바디

1) UnoytStream

ServletInputStream inputStream = request.getInputStream();
String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
  • 요청 메시지 바디 내용 직접 조회

2) HttpEntity

  • 헤더, 바디 정보 조회
  • HttpMessageConverter 사용 -> StringHttpMessageConverter 적용

3) RequestEntity

  • HttpEntity 를 상속, 같은 기능을 함
  • HttpMethod, url 정보가 추가

4) RequestBody

  • 바디 정보 조회
  • HttpMessageConverter 사용 -> StringHttpMessageConverter 적용

JSON -> 문자 변환

InputStream, @RequestBody : Object Mapper

JSON -> 객체 변환

HttpEntity, @RequestBody : Http 메시지 컨버터가 자동 변환


정리

요청 파라미터 조회 : @RequestParam , @ModelAttribute
메시지 바디 조회 : @RequestBody

0개의 댓글