1 정적 컨텐츠
(1) 종류
- 정적 컨텐츠 : 파일 그대로를 클라이언트에 전달
- MVC와 템플릿 엔진 : Model, View, Controller를 사용해 변형 후 클라이언트에 전달
- API : JSON 포멧으로 변형 후 클라이언트에 전달, 서버끼리 데이터 전달
(2) 정적 컨텐츠
- 스프링 부트는 기본으로 정적 컨텐츠 제공
- 입력한 것을 그대로 반환하나 별도의 프로그래밍은 불가함
- hello-static.html
<!DOCTYPE HTML>
<html>
<head>
<title>static content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
정적 컨텐츠 입니다.
</body>
</html>
2 MVC와 템플릿 엔진
(1) MVC
- MVC : Model, View, Controller
- View : 화면을 그리는데 모든 리소스 집중
- Model, Controller : 비지니스 로직 및 리소스 가공에 리소스 집중
(2) hello-template
- 파일구조
- controller에 hello-mvc 추가
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name") String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
}
- hello-template.html
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body></html>
- 오류 출력
(3) hello-template_ 수정
- hello-template.html의 내용이 치환되어 출력
- required는 디폴트가 true, false로 처리 시 파라미터를 안넘겨줘도 오류 발생하지 않음
@GetMapping("hello-mvc")
/* required 디폴트는 true, false로 하면 파라미터를 안넘겨줘도 됨 */
public String helloMvc(@RequestParam(name = "name", required = false) String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
}
3 API
(1) hello-string
- controller에 hello-string 추가
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "hello" + name ; // "hello jeong"
}
- 소스코드를 확인해보면 별도의 html 문법 없이 string 값만 존재하는 것 확인할 수 있음
(2) hello-api
- controller에 hello-api와 Hello class 정의
@GetMapping("hello-api")
@ResponseBody
public Hello helloApi(@RequestParam("name") String name) {
Hello hello = new Hello();
hello.setName(name);
return hello;
}
static class Hello{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- 실행하면 JSON 형식으로 출력됨
(3) 동작원리
- 스프링에서 helloController를 찾아감
- @ResponseBody가 없다면? ViewResolve가 나에게 맞는 템플릿 찾아서 돌려줘
- @ResponseBody가 있다면? http의 BODY에 문자 내용을 직접 반환 > 객체라면 기본이 JSON 형식으로 만들어서!!
- JSONConverter(기본 객체 처리), StringConverter(기본 문자 처리)