>  기사  >  Java  >  Spring Boot 시리즈 웹 개발을 위한 Thymeleaf 및 FreeMarker 템플릿 엔진에 대한 자세한 설명

Spring Boot 시리즈 웹 개발을 위한 Thymeleaf 및 FreeMarker 템플릿 엔진에 대한 자세한 설명

黄舟
黄舟원래의
2018-05-11 14:45:106213검색

이전 기사에서는 json 데이터를 반환하는 좋은 RESTful API를 소개했습니다. 다음으로 처리된 데이터를 페이지에 렌더링하는 방법을 소개합니다.

Spring Boot에서는 템플릿 엔진을 사용합니다.

Spring Boot에서는 Thymeleaf, FreeMarker, Velocity, Groovy, Mustache 등과 같은 템플릿 엔진 사용을 권장합니다. JSP 사용은 권장되지 않습니다.

Spring Boot는 위 엔진에 대한 좋은 기본 구성을 제공합니다. 기본 src/main/resources/templates 디렉터리는 위 템플릿 엔진의 구성 경로입니다.

1. Spring Boot에서 Thymeleaf 템플릿 엔진 사용

소개: Thymeleaf는 Velocity 및 FreeMarker와 유사한 템플릿 엔진으로 웹 및 비웹 환경에서 애플리케이션 개발에 사용할 수 있으며 JSP를 완전히 대체할 수 있습니다.

1. pom.xml

<!-- thymeleaf 模板引擎-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2. 작성 컨트롤러

/**
 * @author sam
 * @since 2017/7/16
 */
@Controller
public class HomeController {

    @RequestMapping("/home")
    public String home(ModelMap modelMap) {

        modelMap.put("name", "Magical Sam");

        List<String> list = new ArrayList<>();
        list.add("sam a");
        list.add("sam b");
        list.add("sam c");
        list.add("sam d");
        modelMap.put("list", list);

        return "home";
    }

}

3. HTML 코드를 작성합니다. 여기서 th:text="${name}"은 thymeleaf의 구문입니다. Thymeleaf 공식 문서

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Home</title>
</head>
<body>
    <span th:text="${name}"></span>
    <ul>
        <li th:each="item : ${list}" th:text="${item}"></li>
    </ul>
</body>
</html>

응용 프로그램을 시작하고 http://localhost:8080/home을 방문하여 해당 결과를 얻으세요.

thymeleaf의 기본 구성을 수정해야 하는 경우 application.properties에 추가할 수 있습니다:

# ================================================
#                   Thymeleaf配置
# ================================================
# 是否启用thymeleaf模板解析
spring.thymeleaf.enabled=true
# 是否开启模板缓存(建议:开发环境下设置为false,生产环境设置为true)
spring.thymeleaf.cache=false 
# Check that the templates location exists.
spring.thymeleaf.check-template-location=true 
# 模板的媒体类型设置,默认为text/html
spring.thymeleaf.content-type=text/html
# 模板的编码设置,默认UTF-8
spring.thymeleaf.encoding=UTF-8
# 设置可以被解析的视图,以逗号,分隔
#spring.thymeleaf.view-names=
# 排除不需要被解析视图,以逗号,分隔
#spring.thymeleaf.excluded-view-names=
# 模板模式设置,默认为HTML5
#spring.thymeleaf.mode=HTML5 
# 前缀设置,SpringBoot默认模板放置在classpath:/template/目录下
spring.thymeleaf.prefix=classpath:/templates/ 
# 后缀设置,默认为.html
spring.thymeleaf.suffix=.html
# 模板在模板链中被解析的顺序
#spring.thymeleaf.template-resolver-order=

2. Spring Boot

1에서 FreeMarker 템플릿 엔진을 사용하여 pom.xml

<!-- freemarker 模板引擎 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2에 종속성을 추가합니다.

同上。

3, 템플릿 아래에 새 home.ftl 파일을 만들고 html 코드를 작성하세요. freemarker 구문은 다음을 참조하세요. FreeMarker 공식 문서

home.ftl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <span>${name}</span>
    <ul>
    <#list list as item >
        <li>${item}</li>
    </#list>
    </ul>
</body>
</html>

애플리케이션을 시작하고 http://localhost를 방문하세요. 8080/home을 사용하여 해당 결과를 얻으세요.

freemarker의 기본 구성을 수정해야 하는 경우 다음을 추가할 수 있습니다.

# ================================================
#                   FreeMarker配置
# ================================================
# 是否开启模板缓存
spring.freemarker.cache=true
# 编码格式
spring.freemarker.charset=UTF-8
# 模板的媒体类型设置
spring.freemarker.content-type=text/html
# 前缀设置 默认为 ""
spring.freemarker.prefix=
# 后缀设置 默认为 .ftl
spring.freemarker.suffix=.ftl
#spring.freemarker.allow-request-override=false
#spring.freemarker.check-template-location=true
#spring.freemarker.expose-request-attributes=false
#spring.freemarker.expose-session-attributes=false
#spring.freemarker.expose-spring-macro-helpers=false
#spring.freemarker.request-context-attribute=
#spring.freemarker.template-loader-path=classpath:/templates/
#spring.freemarker.view-names=
in application.properties

위 내용은 Spring Boot 시리즈 웹 개발을 위한 Thymeleaf 및 FreeMarker 템플릿 엔진에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.