Spring 응답 데이터 1강
Server에서 Client로 Data를 전달하는 방법은 정적 리소스, View Template, HTTP Message Body 세가지 방법이 있다.



정적 리소스
웹 애플리케이션에서 변하지 않는 파일들을 의미한다. 예를 들어, HTML, CSS, JavaScript, 이미지 파일들(JPG, PNG, GIF) 등이 정적 리소스에 해당한다.
/static/public/META-INF/resourcessrc/main/resources/static
src/main/resources/static/hello/world.html 디렉토리 구조라면http://localhost:8080/hello/world.html URL로 리소스에 접근이 가능하다.
View Template
Spring에서는 Thymeleaf, JSP와 같은 템플릿 엔진을 사용해 View Template을 작성할 수 있고, View Template은 서버에서 데이터를 받아 이를 HTML 구조에 맞게 삽입한 후, 최종적으로 클라이언트에게 전송되는 HTML 문서로 변환하여 사용자에게 동적으로 생성된 웹 페이지를 제공한다.
- View Template
View Template은 Model을 참고하여 HTML 등이 동적으로 만들어지고 Client에 응답된다.
Spring Boot는 기본적으로 View Template 경로(src/main/resources/templates)를 설정한다.
build.gradle에 Thymeleaf 의존성을 추가하면 ThymeleafViewResolver와 필요한 Spring Bean들이 자동으로 등록된다.
기본 설정 예시(아래 내용을 자동으로 Spring Boot가 등록해준다.)
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html // or jsp
@ResponseBody 가 없으면 View Resolver가 실행되며 View를 찾고 Rendering한다.@Controller
public class ViewTemplateController {
@RequestMapping("/response-view")
public String responseView(Model model) {
// key, value
model.addAttribute("data", "sparta");
return "thymeleaf-view";
}
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<h1>Thymeleaf</h1>
<h2 th:text="${data}"></h2>
</body>
</html>
ex) http://localhost:8080/response-view

@Controller
public class ViewController {
@ResponseBody // @RestController = @Controller + @ResponseBody
@RequestMapping("/response-body")
public String responseBody() {
return "thymeleaf-view";
}
}

@Controller
public class ViewTemplateController {
// thymeleaf-view.html 과 Mapping된다.
@RequestMapping("/thymeleaf-view")
public void responseViewV2(Model model) {
model.addAttribute("data", "daesan");
}
}
