10. Response
์คํ๋ง์์ ์๋ต ๋ฐ์ดํฐ๋ฅผ ๋ง๋๋ ๋ฐฉ๋ฒ์ ์ ๋ฆฌํด๋ณด์.
1๏ธโฃ ย ์คํ๋ง์ด ์๋ต๋ฐ์ดํฐ๋ฅผ ๋ง๋๋ ๋ฐฉ๋ฒ
- ์คํ๋ง(์๋ฒ)์์ ์๋ต ๋ฐ์ดํฐ๋ฅผ ๋ง๋๋ ๋ฐฉ๋ฒ์ ํฌ๊ฒ 3๊ฐ์ง์ด๋ค.
์๋ต ๋ฐฉ์ | ์์ธ | ์๋ต ๋ฉ์๋ |
---|---|---|
์ ์ ๋ฆฌ์์ค | ์น ๋ธ๋ผ์ฐ์ ์ ์ ์ ์ธ HTML, CSS, js ๋ฅผ ๊ทธ๋๋ก ์ ๊ณตํ๋ ๊ฒฝ์ฐ | ์๋ฒ์์ ํด๋น ํ์ผ์ ๊ทธ๋๋ก ์๋นํ๋ค. |
๋ทฐ ํ ํ๋ฆฟ | JSP๋ ThymeLeaf ๊ฐ์ ๋ทฐ ํ ํ๋ฆฟ์ ๊ฑฐ์ณ์ HTML ์ ์์ฑํ๊ณ , ๋ทฐ๊ฐ ์๋ต์ ๋ง๋ค์ด์ ์ ๊ณตํ๋ ๊ฒฝ์ฐ | ์ปจํธ๋กค๋ฌ์์ Model ๊ฐ์ฒด์ addArtribute ๋ฉ์๋์ ๋ฐ์ดํฐ๋ฅผ ๋ด์ ๋ทฐ ํ ํ๋ฆฟ์ ์ ์กํ๋ค. |
HTTP API | HTTP ๋ฉ์์ง ๋ฐ๋์ ๋ฐ์ดํฐ๋ฅผ ์ง์ ๋ฃ์ด์ ์๋ตํ๋ ๊ฒฝ์ฐ | ResponseEntityยซT>T>, @ResponseBody |
2๏ธโฃ ย ๋ทฐ ํ ํ๋ฆฟ
์์๋ก hello.html ์ ์๋ต์ ๋ฃ์ด ์ ์กํด๋ณด์.
hello.html (ํ์ผ ๊ฒฝ๋ก : resources/templates/response/hello.html)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Title</title>
</head>
<body>
<p th:text="${data}">empty</p>
</body>
</html>
- ${data} ์ ์๋ต ๋ด์ฉ์ด ๋ค์ด๊ฐ๋๋ก model.addAttribute ๋ฉ์๋๋ฅผ ์ด์ฉํ๋ฉด ๋๋ค.
@Controller
public class ResponseViewController {
@RequestMapping("/response-view-v1")
public String responseViewV2(Model model) {
model.addAttribute("data", "hello");
return "response/hello";
}
}
3๏ธโฃ ย HTTP API - ResponseEntityยซT>T>
- ๋ฐํํ์ ์ ์ ๋ค๋ฆญ์ผ๋ก ์ง์ ํ ์ ์๊ณ , HTTP ์ํ์ฝ๋๋ฅผ ์ค์ ํ ์ ์๋ค.
@Controller
public class ResponseBodyController {
@GetMapping("/response-body-string-v2")
public ResponseEntity<String> responserBodyV2() {
return new ResponseEntity<>("ok", HttpStatus.OK);
}
@GetMapping("/response-body-json-v1")
public ResponseEntity<HelloData> responseBodyJsonV1() {
HelloData helloData = new HelloData();
helloData.setUsername("hello");
helloData.setAge(20);
return new ResponseEntity<>(helloData, HttpStatus.OK);
}
}
4๏ธโฃ ย HTTP API - @ResponseBody
์ปจํธ๋กค๋ฌ์์ ๋ฆฌํดํ๋ ๊ฐ์ ๊ทธ๋๋ก HTTP ๋ฉ์์ง ๋ฐ๋์ ๋ฃ์ด ์ ์กํ๋ค.
ResponseEntity ์ ๋ฌ๋ฆฌ ์ํ ์ฝ๋๋ฅผ ์ง์ ํ ์ ์๋ค. @ResponseStatus ์ด๋ ธํ ์ด์ ์ผ๋ก ์ค์ ํ๋ฉด ๋๋ค.
@Controller
public class ResponseBodyController {
@ResponseBody
@GetMapping("/response-body-string-v3")
public String responseBodyV3() {
return "ok";
}
@ResponseStatus(HttpStatus.OK)
@ResponseBody
@GetMapping("/response-body-json-v2")
public HelloData responseBodyJsonV2() {
HelloData helloData = new HelloData();
helloData.setUsername("hello");
helloData.setAge(20);
return helloData;
}
}