진짜 하는 일 없이 그냥 정적 파일을 클라이언트(웹 브라우저)에 반환
📂 /main/resources/static/hello-static.html
hello-static
과 매핑된 컨트롤러를 찾음 → 없어 → resources/static
에서 찾음Model
, View
, Controller
View
는 화면을 그리는데 집중Model
, Controller
는 비지니스 로직, 내부적인 처리에 집중📂 Controller
📂 View
/main/resources/static/hello-templates.html
🖥️http://localhost:8080/hello-mvc?name=나는의연
Thymeleaf 템플릿 장점
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>
ViewResolver
는 뷰를 찾고 템플릿을 연결하는 역할🪄정적 컨텐츠를 제외하고 딱 두 가지만 기억
HTML
로 보낼래? - 뷰를 찾아서 템플릿 엔진을 통해 화면을 렌더링해서 전달API
방식으로 데이터를 보낼래?JSON
, XML
형식으로 데이터를 반환할 때 사용HttpMessageConverter
를 이용해 객체를 JSON, XML으로 변환@RestController
@RequestMapping("/api")
public class ExampleController {
@GetMapping("/user")
@ResponseBody
public User getUser() {
return new User("John", 30);
}
static class User {
private String name;
private int age;
**// 생성자**
public User(String name, int age) {
this.name = name;
this.age = age;
}
**// Getter**
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
}
Spring에서는 객체를 JSON으로 변환할 때 Jackson
라이브러리가 기본적으로 사용
🪄 @Data
어노테이션(Lombok 라이브러리)
@Data
는 getter
, setter
, equals
, hashCode
, toString
을 자동으로 생성해,import lombok.Data;
@Data
static class User{
private String name;
private int age;
}
@ResponseBody
사용시 View Resolver 대신 HTTP Body(응답 메세지 바디)에 문자 내용을 직접 반환
@ResponseBody
를 사용하면ViewResolver
대신에 HttpMessageConverter
가 동작ViewResolver
는 템플릿을 찾아서 반환)StringHttpMessageConverter
MappingJackson2HttpMessageConverter