티스토리 뷰

Thymeleaf

[Thymeleaf ] - Thymeleaf 기본세팅

김종현 2020. 12. 13. 00:26

보통 Spring으로 개발을 하게되면 view단을 JSP를 많이 사용되는데

그 외에 thymeleaf, freemarker, mustache, velocity 등 다양한 템플릿을 가져다 쓰는데 이번글에서는

Thymeleaf(타임리프) 를 적용해보는 시간을 갖도록 하자.

 

Thymeleaf는 JSP와는 달리 서버에서 컴파일 되지않고 바로 웹브라우저에서 해석이 되는데 이는 브라우저가

해석을 할 수 있는 마크업 언어로 이뤄져있기 때문이다. 

 

이제 기본환경을 세팅해보자

pom.xml에 의존성 추가

web 의존성과 thymeleaf 의존성을 각각 pom.xml에 추가하자

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

thymeleaf 설정추가

java config

package com.kjh.study.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.templatemode.TemplateMode;

@Configuration
public class ThymeleafConfig {

    @Bean
    public SpringResourceTemplateResolver springResourceTemplateResolver() {
        SpringResourceTemplateResolver springResourceTemplateResolver = new SpringResourceTemplateResolver();
        springResourceTemplateResolver.setPrefix("classpath:templates/");
        springResourceTemplateResolver.setCharacterEncoding("UTF-8");
        springResourceTemplateResolver.setSuffix(".html");
        springResourceTemplateResolver.setTemplateMode(TemplateMode.HTML);
        springResourceTemplateResolver.setCacheable(false);

        return springResourceTemplateResolver;
    }
}

 

properties config

spring.thymeleaf.prefix=classpath:templates/
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.cache=false

 

java 또는 properties 설정으로 본인이 편한 방식으로 하면된다.

Controller / HTML 파일생성

Controller

package com.kjh.study.controller;

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

@Controller
@RequestMapping("/study")
public class StudyController {

    @GetMapping
    public String study() {
        return "study";
    }
}

 

HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>Hello, Thymeleaf</h1>
</body>
</html>

웹 페이지 띄우기

위 HTML파일을 src/main/resources/templates/하위에 생성을 하고 서버를 가동후 해당 URL로 접근해보자

정상적으로 실행되었다. 다음에는 Thymeleaf의 문법에 대해 알아보자

 

+ 추가내용 (2021.11.14 16:32)

Thymeleaf 디펜던시를 추가해주면 application.properties에 설정한 값들이 default로 잡히게 된다.

 

728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/05   »
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 31
글 보관함