미소를뿌리는감자의 코딩
[Spring] 정적, 동적 html 처리 본문
정적 html은 resouces > static 폴더에 넣어주는 것이 일반적이며,
동적 html은 templates > hello.html 폴더에 넣어주는 것이 일반적이다.
이때, url에 대해서 html 파일을 불러오는 방법을 이야기해 볼 것이다.
1. 정적 html
아래 3가지 방법이 있다.
@Controller
public class HtmlController {
@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";
}
}
첫 번째 방법은 .html 파일을 직접 경로로 가져오는 방법이다.
@GetMapping("/static-hello")
public String hello(){
return "hello.html";
}
직접 html 파일을 찾아 반환하는 방식이다.
정적 파일의 경우, modification이 필요 없기 때문에, controller -> html -> controller -> 반환 하는 과정이 불필요하다.
따라서 return "hello.html" 로 직접 그 파일 언급을 통해서 사용할 수 있다.
이때, build.gradle에서 확인할 수 있는
thymeleaf가 주요 역할을 한다. ( 주석 처리해 놓은 부분 )
thymeleaf를 사용하게 되면, spring boot에서 html을 찾기 위해 templates 폴더 우선적으로 찾아보게 된다.
따라서,, tymeleaf를 켜 놓으면 templates의 hello.html 파일을 반환하게 되며,
켜놓지 않으면 즉, 주석처리 해 놓으면, static의 hello.html 파일이 반환되게 된다.
또한, thymeleaf 를 끄고, return "hello"를 하게 되면, spring boot에서 대상을 찾지 못한다.
hello.html을 해줘야지, 폴더에서 hello.html을 찾을 수 있다.
두 번째 방법으로 넘어가 보자,
@GetMapping("/html/redirect")
public String htmlStatic() {
return "redirect:/hello.html";
}
이를 이용하게 되면, url /html/redirect로 접근할 수 있지만, 표면상으로만 그럴 뿐 redirect:/hello.html을 통해서 hello.html 파일을 반환하는 방법이다.
세 번째 방법은
.html을 사용하지 않고도 원하는 파일에 접근하는 방법이다.
thymeleaf 는 기본적으로 templates 폴더에 있는 hello.html을 찾아서 반환해준다. 따라서, .html을 붙이지 않아도 파일을 찾아서 반환해 준다.
@GetMapping("/html/templates")
public String htmlTemplates() {
return "hello";
}
2. 동적 html
private static long visitCount = 0;
@GetMapping("/html/dynamic")
public String htmlDynamic(Model model) {
visitCount++;
model.addAttribute("visits", visitCount);
return "hello-visit";
}
동적으로 변화하는 것을 알기 위해 visitCount라는 변수를 하나 선언해 주었다.
이 Model을 이용해 주었다.
이후,
model.addAttribute("visits", visitCount);
이것을 통해 "visits"라는 변수에 visitCount 값을 넣어주고...
return "hello-visit"을 통해 다시 반환해 주었다.
Model 이 무엇인가 이해가 잘 안되어서 구글링을 해보았다.
" a holder of the context data passed by a Controller to be displayed on a View "
라고 했다.
즉, display 되기 위해, Controller에서 생성된 데이터를 담는 '그릇' 으로 이해하면 될 것 같다.
그리고 이를 view로 전달해주는 역할을 하는 녀석이다.
model.addAttribute("visits", visitCount); 에서 생긴 의문점이 있다.
어떻게 visits 하나 만으로 templates 폴더 아래 있는 html 파일에 있는 visit을 찾는 것일까?
아마 return "hello-visit"; 을 통해, hello-visit.html에 있음을 하는 것일까?
Thymeleaf에서 ${attributeName} 으로 되어 있는 것을 통해 접근하는 것 같다.
"In Thymeleaf, these model attributes can be accessed with the following syntax: `${attributeName}` which is a Spring EL expression"
아래 article에서 정보를 더 찾을 수 있다.
https://www.javacodegeeks.com/2014/05/spring-mvc-and-thymeleaf-how-to-acess-data-from-templates.html
'강의수강 > [Spring]' 카테고리의 다른 글
[Spring] Jackson ( Jason to Object, Object to Jason ) (1) | 2024.02.29 |
---|---|
[Spring] Response Json (0) | 2024.02.29 |
[Spring] Annotations 모음 (0) | 2024.02.29 |
[Spring] 단축키 모음 (0) | 2024.02.29 |
[Spring] Various annotations (0) | 2024.02.29 |