Backend/Spring

[Spring boot] Spring boot에서 Thymeleaf 사용

나는 유찌 2020. 2. 23. 10:51

 

 

Spring boot로 회사 프로젝트를 진행하였다. 기존 코드가 있는 상황이었던 터라 설정은 건드리지 않았었다.

집에서 따로 Spring boot 템플릿 엔진을 타임리프로 무언가를 만드려던 중 설정에서 막혀버렸다 ;_;

이거 하나 해결하는데도 쪼렙 개발자는 상당 시간을 투자했다.

 

그래서 오늘은 내가 해결한 Spring boot 템플릿엔진으로 타임리프를 사용하는 방법을 포스팅한다.

 

 

 

 


 

1. dependency 추가

 

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

 

 

 

2. application.properties

 

spring.thymeleaf.cache=false
spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

 

 

1) spring.thymeleaf.cache

false로 해놓았을 때 타임리프를 수정하고 서버를 재시작할 필요 없이 새로 고침만으로 반영이 된다.

(서버 재시작을 안 해도 되어 매우 편리하다!)

개발할 때는 false로 두고 반영 시에는 true로 설정해놓는 게 좋다.

 

 

2) spring.thymeleaf.enabled

타임리프를 사용하겠다는 뜻이다.

당연히 true로 설정해둔다.

 

 

3) spring.thymeleaf.prefix

경로를 잡아준다.

나의 경우 'classpath:/templates/'로 설정해둔 게 보인다.

혹시 몰라 프로젝트 구조를 같이 첨부해두겠다.

resources 폴더 밑 templates 폴더가 보이고 그 밑으로 html 파일이 있는 것을 확인할 수 있다.

 

 

4) spring.thymeleaf.suffix

나는 html을 사용했기 때문에 '. html'로 설정해두었다.

만일 jsp를 사용한다면 '. jsp'를 입력해주면 되겠다.

 

 

 

3. ViewResolver

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Configuration
@EnableWebMvc
public class ViewConfig extends WebMvcConfigurerAdapter {
    @Bean
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("classpath:/templates/");
        resolver.setSuffix(".html");
        return resolver;
    }
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}
 

java 폴더 밑으로 config 폴더를 만들어 안에 ViewResolver 파일을 만들어준다.