https://github.com/lay423/springmvc/commit/58688e215d2838d1f851b3fd5da9d28ef55e8946
https://github.com/lay423/springmvc/commit/1675e562c6a10c984b41d22415c14b80d14605a4
RequestHeaderController 실행
: request=org.apache.catalina.connector.RequestFacade@1b21625f
: response=org.apache.catalina.connector.ResponseFacade@4920491f
: httpMethod=GET
: locale=ko_KR
: headerMap={content-type=[application/json], user-agent=[PostmanRuntime/7.29.2], accept=[*/*], postman-token=[6aee894f-dc1a-491a-ab2b-733ccf7fc472], host=[localhost:8080], accept-encoding=[gzip, deflate, br], connection=[keep-alive], content-length=[32]}
: header host=localhost:8080
: myCookie=null
MultiValueMap<String, String>
MAP과 유사한데, 하나의 키에 여러 값을 받을 수 있다.
HTTP header, http 쿼리 파라미터와 같이 하나의 키에 여러 값을 받을 때 사용한다.
요청 파라미터 - 쿼리 파라미터 HTML Form
RequestParamController 실행
http://localhost:8080/request-param-v1?username=hello&age=20
@RequestParam(required = false) Integer age)
기본형에 null 입력
int 에 null 입력하는 것은 불가능하므로 Integer로 선언
requestParamDefault
빈 문자의 경우에도 설정한 기본 값이 적용된다.
requestParamMap
파라미터를 Map, MultiValueMap으로 조회할 수 있다.
@ResponseBody
@RequestMapping("/model-attribute-v1")
public String modelAttributeV1(@ModelAttribute HelloData helloData) {
log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
return "ok";
}
스프링 MVC는 ModelAttribute 가 있으면 다음을 실행한다.
@ResponseBody
@RequestMapping("/model-attribute-v2")
public String modelAttributeV2(HelloData helloData) {
log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
return "ok";
}
@ModelAttribute는 생략할 수 있다.
HTTP message body 에 데이터를 직접 담아서 요청
@PostMapping("/request-body-string-v3")
public HttpEntity<String> requestBodyStringV3(HttpEntity<String> httpEntity) throws IOException {
String messageBody = httpEntity.getBody();
log.info("messageBody={}", messageBody);
return new HttpEntity<>("ok");
}
"스프링 MVC는 다음 파라미터를 지원한다."
HttpEntity: HTTP header, body 정보를 편리하게 조회
HttpEntity는 응답에도 사용 가능
@ResponseBody
@PostMapping("/request-body-string-v4")
public String requestBodyStringV4(@RequestBody String messageBody) {
log.info("messageBody={}", messageBody);
return "ok";
}
"@RequestBody"
@RequestBody를 사용하면 HTTP 메시지 바디 정보를 편리하게 조회할 수 있다. 참고로 헤더 정보가 필요하다면 Http를 사용하거나 @RequestHeader를 사용하면 된다.
요청 파라미터를 조회하는 @RequestParam 과 @ModelAttribute와는 전혀 관계가 없다.
"요청 파라미터 vs HTTP 메시지 바디"
요청 파라미터를 조회하는 기능: @RequestParam, @ModelAttribute
HTTP 메시지 바디를 직접 조회하는 기능: @RequestBody
"@ResponseBody"
@ResponseBody를 사용하면 응답 결과를 HTTP 메시지 바디에 직접 담아서 전달할 수 있다.
물론 이 경우에도 view를 사용하지 않는다.