본문 바로가기
백엔드/SpringBoot

Thymeleaf 템플릿 적용하기

by 1005ptr 2020. 12. 20.
반응형

1. pom.xml에 dependency 추가

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
    <groupId>nz.net.ultraq.thymeleaf</groupId>
    <artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>

2. Thymeleaf Configuration 만들기

@Configuration
public class ThymeleafViewResolverConfig {

	@Bean
	public SpringResourceTemplateResolver templateResolver() {
		SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
		templateResolver.setPrefix("classpath:templates/");
		templateResolver.setCharacterEncoding("UTF-8");
		templateResolver.setSuffix(".html");
		templateResolver.setTemplateMode("HTML5");
		templateResolver.setCacheable(false);
		return templateResolver;
	}

	@Bean
	public SpringTemplateEngine templateEngine(MessageSource messageSource) {
		SpringTemplateEngine templateEngine = new SpringTemplateEngine();
		templateEngine.setTemplateResolver(templateResolver());
		templateEngine.setTemplateEngineMessageSource(messageSource);
		templateEngine.addDialect(layoutDialect());

		return templateEngine;
	}

	@Bean
	public LayoutDialect layoutDialect() {
		return new LayoutDialect();
	}

	@Bean
	@Autowired
	public ViewResolver viewResolver(MessageSource messageSource) {
		ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
		viewResolver.setTemplateEngine(templateEngine(messageSource));
		viewResolver.setCharacterEncoding("UTF-8");
		viewResolver.setOrder(0);
		return viewResolver;
	}
}

3. 컨트롤러, 서비스, 화면 생성

  • @Controller로 컨트롤러 생성
  • @Service로 서비스 생성
  • 화면 경로는 src/main/resources 아래에 templates 폴더

src/main/resources의 template 폴더와 static 폴더의 사용 용도 구분은 학습이 필요하다.

짧게 읽어본 바로는 js,css는 static에 들어가고 template에 html이 들어있었다.

반응형

댓글