springboot系列之模板引擎thymeleaf

页面模板引擎有JSP、Velocity、Freemarker、Thymeleaf等等,在springboot中,推荐使用Thymeleaf模板引擎,因为thymeleaf语法更简单,功能更强大。

一、引入thymeleaf

在pom.xml文件中引入thymeleaf依赖,如下:

<properties>
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <!-- 布局功能的支持程序  thymeleaf3主程序  layout2以上版本 -->
    <thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>


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

二、thymeleaf的基本使用

在使用thymeleaf时,我们只要把html页面放在classpath:/resources/templates下面,thymeleaf就能自动渲染;如果启动项目时,页面无法访问报404,有可能是thymeleaf版本和springboot版本不一致导致,springboot版本和thymeleaf版本有很大的关系会影响到页面,导致报404无法找到页面。

1、在html页面中导入thymeleaf的命名空间:<html xmlns:th="http://www.thymeleaf.org">

controller:

@Controller
@RequestMapping("/first")
public class HelloWorldController {
    private Logger logger = LoggerFactory.getLogger(HelloWorldController.class);

    @RequestMapping("/test1")
    public String sayHello(Model model) {
        model.addAttribute("hello","hello thymeleaf!!!");
        return "test";
    }
}

thymeleaf页面如下:

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

<head>
    <meta charset="UTF-8"/>
    <title>测试thymeleaf的基本使用</title>
</head>
<body>
从
<span th:text="${hello}"> </span>
</body>
</html>

启动项目,进行访问,效果如下:

2、thymeleaf基本语法
基础语法参见thymeleaf官方文档:https://www.thymeleaf.org/documentation.html

原文地址:https://www.cnblogs.com/jasonboren/p/14883403.html