웹을 개발하는 방법으로 크게 3가지가 존재한다.
1. 정적 컨텐츠
2. MVC와 템플릿 엔진
3. API
Spring Boot는 /static 폴더에서 정적 컨텐츠 기능을 자동으로 제공한다. 예를 들어 이 폴더 안에 hello.html 파일을 작성하고, localhost:8080/hello.html에 들어가면 파일 내용이 그대로 전달된 것을 볼 수 있다.
전체적인 과정의 큰 틀을 살펴보자.
MVC : Model, View, Controller
View는 화면을 그리고, Model이나 Controller는 내부적인 것을 처리하는 데에 집중한다. Controller는 Business logic이나 서버에 관련된 일을 처리하고 Model에 화면과 관련된 필요한 정보를 담아 넘겨준다.
(Business logic : 데이터가 어떻게 생성되고 저장되고 수정되는지를 정의한 것)
(Window) Ctrl + P : parameter 정보
HelloController.java
@Controller
public class HelloController {
@GetMapping("hello-mvc")
// 이번엔 외부 parameter를 통해 data를 받음.
public String helloMvc(@RequestParam("name") String name, Model model) {
model.addAttribute("name", name);
return "hello-template"; // hello-template.html
}
}
hello-template.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}"></p>
</body>
이 상태에서 localhost:8080/hello-mvc에 접속하면 아래와 같이 오류가 뜬다.
아래와 같이 parameter인 name 뒤에 data를 넘겨주어야 한다.
data로 spring을 주었다.
전체적인 과정을 살펴보자.
템플릿 엔진과는 달리 view를 거치지 않고 data를 client에게 직접 내린다.
HelloController.java
@Controller
public class HelloController {
@GetMapping("hello-string")
//API 방식
@ResponseBody //http의 body 부분에 data를 직접 넣겠다.
public String helloString(@RequestParam("name") String name) {
return "hello " + name; //name에 data를 넣어주면 hello data로 변환.
}
}
아래처럼 페이지 소스를 보면 html 태그가 하나도 없는 걸 확인할 수 있다.
실제 api 방식을 사용하여 data를 넘겨보자.
HelloController.java
@Controller
public class HelloController {
@GetMapping("hello-api")
@ResponseBody
public Hello hellApi(@RequestParam("name") String name) {
Hello hello = new Hello();
hello.setName(name);
return hello; //객체를 넘김.
}
static class Hello {
private String name; //key
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
아래와 같이 JSON 형태로 나타나게 된다.
(JSON : 인터넷에서 자료를 주고받을 때 그 자료를 표현하는 방법. ex) key와 value 쌍인 collection)
@ResponseBody 사용 시