티스토리 뷰

[Spring] thymeleaf 사용하기 (1)

thymeleaf 기초 설정

- templetes 폴더에서 정적 파일 불러오기

-View Mapping Controller 생성

 


 

Thymeleaf 란?

- spring 기반 웹 애플리케이션의 view에서 html, xml, javascript, css, text 처리 후 웹 브라우저에 표시할 때 이용되는 템플릿 엔진의 일종.

- JSP보다 빠르다는 장점이 있으며, spring boot와 같이 많이 사용함.

 

 

(1) thymeleaf 기초 설정하기 - build.gradle

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-web'
}

 

 

(2) src/main/resources/templates 에 html 파일 추가

     src/main/resources/static 에 html 파일 관련 css/js/img 파일 추가

 

 

(3) src/main/java/프로젝트 패키지/config/MvcConfiguration 생성

 

Error page

 

처음엔 MvcConfiguration 설정 없이 그냥 실행했는데, 페이지 연결이 안되고

위의 화면과 같은 에러 페이지(Whitelabel Error Page) 만 떠서

어떤 부분이 문제인지 찾아보니 기존에는 static 파일들에서만 정적 파일(html)들을 불러오기 때문에

MvcConfiguration 클래스를 생성해 templates 파일에서도 불러올 수 있도록 관련 설정을 변경 해주어야 한다는 것을 알게되었다.

 

import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.concurrent.TimeUnit;

@Configuration
public class MvcConfiguration implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/templates/", "classpath:/static/")
                .setCacheControl(CacheControl.maxAge(10, TimeUnit.MINUTES));
    }
}

 

 

(4) html 태그에 thymeleaf 설정 (view로 사용할 html 파일에 전부 설정해주어야 함)

<html xmlns:th="http://www.thymeleaf.org">

 

 

(5) 사용할 static 파일들을 thymeleaf 태그를 이용해 연결

    <link th:href="@{/css/style.css}" rel="stylesheet">

 

 

(6) Controller class 생성 및 View Mapping

- index.html을 mapping한 예시 class입니다.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class IndexController {
    @GetMapping("/index")
    public String index() {
        return "index";
    }
}

 

(7) 실행

- 실행하면 정상적으로 페이지가 뜨는 걸 확인할 수 있습니다.

 

 

 

Reference ✨

bottom-to-top.tistory.com/38

 

Spring Boot HTML 파일 templates에서도 읽도록 설정하기

static 아닌 폴더에서 정적 정보 읽어오기 스프링 부트에 web 의존성을 추가하고 localhost:8080 으로 접근하면 기본적으로 resources 폴더에 있는 static 에 위치한 index.html 파일을 읽게됩니다. 프로젝트를

bottom-to-top.tistory.com

 

댓글
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Total
Today
Yesterday
공지사항
최근에 올라온 글