안녕하세요, 오늘은 입문주차 강의자료를 바탕으로 정적페이지와 동적페이지에 대해 다시 정리해보았습니다.
정적 페이지 처리하기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello Spring</title>
</head>
<body>
Hello, Spring 정적 웹 페이지!! (static)
</body>
</html>
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf’
해당 dependency를 주석 처리해야 테스트가 가능합니다.thymeleaf
는 동적 페이지 처리를 위한 템플릿 엔진입니다. 추가하면 자동으로 Controller에서 html 파일 찾는 경로를/resources/templates
로 설정합니다.@GetMapping("/static-hello")
public String hello() {
return "hello.html";
}
@GetMapping("/html/redirect")
public String htmlStatic() {
return "redirect:/hello.html";
}
템플릿 엔진을 적용한 상태에서 static 폴더의 html 파일을 Controller를 통해서 처리하고 싶다면 이렇게 "redirect:/hello.html" redirect 요청을 문자열로 반환하면 http://localhost:8080/hello.html 요청이 재 수행되면서 static 폴더의 파일을 반환할 수 있습니다.
@GetMapping("/html/templates")
public String htmlTemplates() {
return "hello";
}
타임리프 default 설정
/resources/templates/hello.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello Spring</title>
</head>
<body>
Hello, Spring 정적 웹 페이지!! (templates)
</body>
</html>
동적 페이지 처리하기
http://localhost:8080/html/dynamic
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Hello Spring</title></head>
<body>
<div>
Hello, Spring 동적 웹 페이지!!
</div>
<div>
(방문자 수: <span th:text="${visits}"></span>)
</div>
</body>
</html>
private static long visitCount = 0;
...
@GetMapping("/html/dynamic")
public String htmlDynamic(Model model) {
visitCount++;
model.addAttribute("visits", visitCount);
return "hello-visit";
}
<div>
(방문자 수: <span th:text="${visits}"></span>)
</div>
<div>
(방문자 수: <span>1000000</span>)
</div>
package com.sparta.springmvc.html;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HtmlController {
private static long visitCount = 0;
@GetMapping("/static-hello")
public String hello() {
return "hello.html";
}
@GetMapping("/html/redirect")
public String htmlStatic() {
return "redirect:/hello.html";
}
@GetMapping("/html/templates")
public String htmlTemplates() {
return "hello";
}
@GetMapping("/html/dynamic")
public String htmlDynamic(Model model) {
visitCount++;
model.addAttribute("visits", visitCount);
return "hello-visit";
}
}