Spring/Springboot-Intellij

[SpringBoot] Spring MVC - 정적 페이지(thymeleaf, redirect, template)와 동적 페이지(Model)

congs 2025. 1. 29. 22:22

 

정적 페이지 생성

project - resources - static - HTML file생성
hello이름으로 HTML파일 생성 - 코드 넣기

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello Spring</title>
</head>
<body>
Hello, Spring 정적 웹 페이지!! (static)
</body>
</html>

 

Controller 생성 ( static폴더에 있는 html파일에 접근하는 방법 )

  1. thymeleaf가 걸려있지 않은 상황에서 
    1. http://localhost:8080/hello.html로 직접접근
    2. http://localhost:8080/static-hello로 controller를 타고 찾아서 접근
  2. thymeleaf가 있는 상황에서
    1. http://localhost:8080/hello.html로 직접접근
    2.  

 

thymeleaf가 걸려있지 않은 상황

새롭게 html패키지를 만들고, HtmlController생성!
http://localhost:8080/static-hello 이동시 볼 수 있음 ( hello.html로 이동도 가능)


중요! html(정적 페이지)은 이미 변화가 일어나지 않기 때문에, 굳이 controller를 거칠 필요가 없음!

= thymeleaf 이용하여 controller를 타지말자!


↓ thymeleaf가 걸린 상황

 thymeleaf 

  • 자바 기반의 템플릿 엔진, HTML, XML, JavaScript, CSS 등의 뷰(View) 파일을 동적으로 렌더링하는 데 사용
  • 서버사이드에서 데이터를 가공하여 동적으로 HTML을 생성하는 역할
  • 사용 방법) build.gradle - dependencies에 implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' 

1 ) 직접 접근하는 방법


thymeleaf를 이용하면, 이전처럼 /static-hello로 주소를 쓰면 templetes를 찾을 수 없다는 오류가 뜨는데,

이는 http://localhost:8080/hello.html 직접 접근하면 들어갈 수 있음!

개발자 도구에서 templates를 찾을 수 없다고 설명
resources - templates에 없다는 말!
hello.html로 직접 접근을 하면 찾을 있음

 

2) controller를 타고 접근하는 방법 = redirect 이용하기

(직접 접근하는 경로로 다시 요청하세요 : redirect)

  • 사용 이유 1) html파일의 이름이 바뀌는 경우 - 서버내에서만 바꾸면 되니까
  • 사용 이유 2) 서버내에서 이동 경로 이름을 알리고 싶지 않은 경우

@GetMapping("/html/redirect")
    public String htmlStatic(){
        return "redirect:/hello.html";
    }

http://localhost:8080/html/redirect 로 주소를 치면!

status code가 302 = redirect 코드

 

3) Template engine 에 View 전달

resources - templates폴더 - html파일 생성

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello Spring</title>
</head>
<body>
Hello, Spring 정적 웹 페이지!! (template)
</body>
</html>

  • controller에서 @GetMapping("/html/templates")
  • return값을 .html을 제외한 문자열로만 작성해도 자동으로 붙어있다고 생각
  • 즉, controller라는 annotation이 달린 class에서 - template에 들어가있는 html을 찾을때는 - html앞에 문자열을 넣기

 


 

동적 페이지 

  1. client의 요청을 controller에서 Model로 처리
  2. Template engine(Thymeleaf)에게 view(html파일), model(view에 적용하는 데이터) 전달
  3. Template
    1. ViewModel을 적용 → 동적 웹페이지 생성
    2. 예 ) 로그인 성공 시, "로그인된 사용자의 Nickname"을 페이지에 추가
    3. Template engine 종류: 타임리프(Thymeleaf), Groovy, FreeMarker, Jade, JSP 등
  4. Client(브라우저)에게 View(동적 웹 페이지, HTML)를 전달

Model model에 데이터를 넣어서 보냄


template에 hello-visit이라는 html파일 생성

.html파일에서 model에 담아온 데이터 값을 ${visits}에 넣어서 보여줌!

<!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>

F5를 할수록 방문자 수가 늘어가는 것을 확인!