HTTP 요청 종류 (클라이언트 → 서버 데이터 전달 방식)
1. GET + 쿼리 파라미터
- url에? 사용하여 쿼리 파라미터 전달
2. POST + HTML Form
- HTML <form>의 입력값을 쿼리 파라미터로 만들어 HTTP Body에 넣어 전달
- Content-type: application/x-www-form-urlencoded
3. HTTP Body 데이터
- HTTP Body에 json, xml, text 등의 형태로 전달
- HTTP API에서 사용, 주로 json (Content-type: application/json)
1. GET + 쿼리 파라미터 / 2. POST + HTML Form (쿼리 파라미터) 처리
request.getParameter("XXX");
- HttpServletRequest가 제공하는 getParameter 메서드 사용
@RequestParam
- @RequestParam("XXX") String XXX <=> String XXX = request.getParameter("XXX");
- 파라미터 이름으로 바인딩
- name = "파라미터명" 속성 사용
- 파라미터 명 = 변수 명 이면 name = "파라미터명" 생략 가능
- 변수의 타입이 단순 타입이면 @RequestParam도 생략 가능
- required = true/false로 필수 값 지정 가능, true가 기본
- defaultvalue = "기본값"으로 기본값 지정가능 => defaultvalue를 지정하면 required는 의미 없음
- @RequestParam("age") int age : null을 int형에 받는 것은 불가능(예외 발생) → null을 받을 수 있는 Integer나, defaultValue로 기본값을 지정
@ModelAttribute
- 요청 파라미터 값을 데이터 객체에 자동 바인딩
- 파라미터 명으로 데이터 객체의 변수를 찾아서 값 세팅 (setter 사용)
1) 객체를 생성
2) 요청 파라미터의 이름을 사용해서 해당 객체의 setter를 호출하여 값을 바인딜
@Controller
public class RequestParamController {
private Logger log = LoggerFactory.getLogger(getClass());
// request.getParameter 메서드를 사용하여 세팅
@RequestMapping("/request-param-v1")
public void requestParamV1(HttpServletRequest request, HttpServletResponse response) throws IOException {
String username = request.getParameter("username");
int age = Integer.parseInt(request.getParameter("age"));
log.info("username={}, age={}", username, age);
response.getWriter().write("ok");
}
// @RequestParam 사용
@RequestMapping("/request-param-v2")
public String requestParamV2(@RequestParam("username") String memberName, @RequestParam("age") int memberAge) {
log.info("username={}, age={}", memberName, memberAge);
return "ok";
}
// @RequestParam 사용 : 변수명과 HTTP 파라미터명이 같으면 name="XXXX" 생략가능
@ResponseBody
@RequestMapping("/request-param-v3")
public String requestParamV3(@RequestParam String username, @RequestParam int age) {
log.info("username={}, age={}", username, age);
return "ok";
}
// @RequestParam 사용 : 변수가 단순 타입(String, int ...)이면 RequestParam 생략가능
@ResponseBody
@RequestMapping("/request-param-v4")
public String requestParamV4(String username, int age) {
log.info("username={}, age={}", username, age);
return "ok";
}
// ----------------------------------------------------------
// required = true : 필수값 (기본), required = false : 필수X (전달안하면 NULL 저장됨)
@ResponseBody
@RequestMapping("/request-param-required")
public String requestParamRequired(
@RequestParam(value = "username", required = true) String username,
@RequestParam(value = "age", required = false) Integer age) {
log.info("username={}, age={}", username, age);
return "ok";
}
// defaultValue = "기본값" : 기본값을 지정할 수 있음
@ResponseBody
@RequestMapping("/request-param-defaultValue")
public String requestParamDefaultValue(
@RequestParam(value = "username", defaultValue = "userA") String username,
@RequestParam(value = "age", defaultValue = "-1") int age) {
log.info("username={}, age={}", username, age);
return "ok";
}
// @RequestParam Map<String, Object> paramMap : 모든 파라미터를 Map에 key-value 로 저장
@ResponseBody
@RequestMapping("/request-param-map")
public String requestParamMap(
@RequestParam Map<String, Object> paramMap) {
log.info("username={}, age={}", paramMap.get("username"), paramMap.get("age"));
return "ok";
}
// ----------------------------------------------------------
// @ModelAttribute : 요청 파라미터를 받아서 객체를 만들고(HelloData) 해당 객체에 값을 넣어서 바인딩(set메서드 활용)
@ResponseBody
@RequestMapping("/model-attribute-v1")
public String modelAttributeV1(@ModelAttribute HelloData helloData) {
log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
return "ok";
}
@ResponseBody
@RequestMapping("/model-attribute-v2")
public String modelAttributeV2(HelloData helloData) {
log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
return "ok";
}
}
3. HTTP Body 데이터
InputStrem
ServletInputStream inputStream = request.getInputStream();
String msgBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
HttpEntity
- HTTP header, body정보를 조회 가능
- body직접 조회 / 직접 반환 가능
public HttpEntity<String> httpEntityTest(HttpEntity<String> httpEntity) {
String msgBody = httpEntity.getBody();
return new HttpEntity<>("ok");
}
HttpEntity를 상속받은 객체
RequestEntity : 요청에 사용
ResponseEntity : 응답에 사용, HTTP 상태 코드 설정 가능
return ResponseEntity<String>("Hello Hi", responseHeaders, HttpStatus.CREATED)
@RequestBody
- HTTP 요청의 바디 정보를 편리하게 조회할 수 있음 (json → String / 객체)
- JSON요청 데이터 → HTTP메시지 컨버터 → 객체 (@RequestBody HelloData helloData) => ObjectMapper의 역할 대체
- 생략 불가능
* HTTPEntity나 @RequestBody를 사용하면 HTTP 메시지 컨버터가 HTTP body 내용을 문자나 객체로 바꿔줌
@ResponseBody
- 컨트롤러의 처리 결과를 HTTP 바디에 직접 넣어서 전달 가능 (String / 객체 → json)
- 객체 → HTTP메시지 컨버터 → JSON응답 데이터
3-1) 일반 텍스트
@Controller
public class RequestBodyStringController {
@PostMapping("/request-body-string-v1")
public void requestBodyStringV1(HttpServletRequest request, HttpServletResponse response) throws IOException {
ServletInputStream inputStream = request.getInputStream();
String msgBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
}
@PostMapping("/request-body-string-v2")
public void requestBodyStringV2(InputStream inputStream, Writer responseWrite) throws IOException {
String msgBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
}
@PostMapping("/request-body-string-v3")
public HttpEntity<String> requestBodyStringV3(HttpEntity<String> httpEntity) {
String msgBody = httpEntity.getBody();
return new HttpEntity<>("ok");
}
@PostMapping("/request-body-string-v4")
public String requestBodyStringV4(@RequestBody String msgBody) {
return "ok";
}
}
3-2) json
@PostMapping("/request-body-json-v1")
public void requestBodyJsonV1(HttpServletRequest request, HttpServletResponse response) throws IOException {
ServletInputStream inputStream = request.getInputStream();
String msgBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
HelloData helloData = objectMapper.readValue(msgBody, HelloData.class);
log.info("helloData = {}", helloData);
response.getWriter().write("ok");
}
@ResponseBody
@PostMapping("/request-body-json-v2")
public String requestBodyJsonV2(@RequestBody String msgBody) throws JsonProcessingException {
HelloData helloData = objectMapper.readValue(msgBody, HelloData.class);
log.info("helloData = {}", helloData);
return "ok";
}
@ResponseBody
@PostMapping("/request-body-json-v3")
public String requestBodyJsonV3(HttpEntity<HelloData> httpEntity) {
HelloData helloData = httpEntity.getBody();
log.info("helloData = {}", helloData);
return "ok";
}
@ResponseBody
@PostMapping("/request-body-json-v4")
public String requestBodyJsonV4(@RequestBody HelloData helloData) {
log.info("helloData = {}", helloData);
return "ok";
}
@ResponseBody
@PostMapping("/request-body-json-v3")
public HelloData requestBodyJsonV3(@RequestBody HelloData helloData) {
log.info("helloData = {}", helloData);
return helloData;
}
쿼리 스트링 요청 처리 : @RequestParam, @ModelAttribute
HTTP바디 메시지 조회 : @RequestBody
HTTP바디 메시지 응답 : @ResponseBody
'WEB > spring' 카테고리의 다른 글
[Spring] HTTP응답 처리, ResponseEntity, @ResponseBody, @RestController (0) | 2021.07.28 |
---|---|
[Spring] @PathVariable (0) | 2021.05.30 |
[Spring] 스프링 부트 로깅, slf4j, logback (0) | 2021.05.30 |
[Spring] Spring MVC구조, Spring 동작원리, DispatherServlet (0) | 2021.05.30 |
[Spring] 스프링 빈 생명주기와 콜백 메서드, @PostConstruct, @PreDestroy (0) | 2021.04.18 |