MVC 프레임워크 15

Mar 10, 2023

2 mins read

HTTP 응답 - 정적 리소스, 뷰 템플릿

  • 스프링(서버)에서 응답 데이터를 만드는 방법 3가지
    • 정적 리소스 : 웹 브라우저에 정적인 HTML, css, js를 제공할 때
    • 뷰 템플릿 : 웹 브라우저에 동적인 HTML을 제공할 때
    • HTTP 메시지 : HTTP API를 제공하는 경우(데이터를 전달) HTTP 메시지 바디에 JSON 같은 형식으로 응답

1. 정적 리소스

  • 스프링 부트에서 정적 리소스를 제공하는 클래스 패스 : /static , /public , /resources , /META-INF/resources
  • 정적 리소스 경로 : src/main/resources/static
  • ex) src/main/resources/static/basic/hello-form.html 파일
    웹브라우저 실행 : http://localhost:8080/basic/hello-form.html
  • 정적 리소스는 해당 파일을 변경 없이 그대로 서비스하는 것이다.

2. 뷰 템플릿

  • 스프링 부트 기본 뷰 템플릿 경로 : src/main/resources/templates
  • 뷰 템블릿 생성 : src/main/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>
  • hello.html 뷰 템플릿을 호출하는 컨트롤러 생성
package hello.springmvc.basic.response;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ResponseViewController {
	@RequestMapping("/response-view-v1")
	public ModelAndView responseViewV1() {
		ModelAndView mav = new ModelAndView("response/hello").addObject("data", "hello!");
		return mav;
	}
	
	@RequestMapping("/response-view-v2")
	public String responseViewV2(Model model) {
		model.addAttribute("data", "hello!");
		return "response/hello";
	}
	
	@RequestMapping("/response/hello")
	public void responseViewV3(Model model) {
		model.addAttribute("data", "hello!");
	}
}

Thymeleaf 스프링 부트 설정