SpringBoot引入thymeleaf模板

x33g5p2x  于2021-03-14 发布在 Spring  
字(2.2k)|赞(0)|评价(0)|浏览(389)

SpringBoot项目默认不是Web项目而是使用jar包,而且使用的还是嵌入式的Tomcat,所以是不支持jsp的。
我们可以引入模板引擎来替换jsp,常见的模板引擎有:JSP(jsp本身就是一个模板引擎)、Velocity.、Freemarker.、Thymeleaf。所有的模板引擎的思想如下图,将数据与模板结合,然后通过引擎渲染出最终结果。
<br/>
SpringBoot推荐使用Thymeleaf模板引擎,Thymeleaf官网
1. 引入thymeleaf依赖
`pom.xml

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

```
**2. thymeleaf模板文件**
当你建立SpringBoot项目后,你可以在ThymeleafProperties类中找到该模板在SpringBoot中默认配置,如下:
![](http://img.saoniuhuo.com/images/202108/17501629902606190.jpg)
![](http://img.saoniuhuo.com/images/202108/29991629902606539.jpg)
`ThymeleafProperties.java

````java
@ConfigurationProperties(
// 说明当你在application.properties或application.yml对Thymeleaf进行自己的配置时
// 应该以spring.thymeleaf为前缀的配置
prefix = "spring.thymeleaf" 
)
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING;
public static final String DEFAULT_PREFIX = "classpath:/templates/"; // 说明thymeleaf模板文件默认放在resources/templates/目录
public static final String DEFAULT_SUFFIX = ".html"; // 说明模板文件的后缀为 .html
private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
private String prefix = "classpath:/templates/"; 
private String suffix = ".html";
private String mode = "HTML";
private Charset encoding;
private boolean cache;

```
`resources/templates/index.html

````html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>欢迎使用Thymeleaf</h1>
</body>
</html>

```
**3. 在Controller中访问index.html**
`com/example/thymeleaf/controller/IndexController.java

````java
package com.example.thymeleaf.controller;

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

@Controller
public class IndexController {

    @RequestMapping(value = "/index")
    public String index() {
        return "index"; // 会自动找到位于templates/index.html 
    }
}

```
启动项目,访问 http://localhost:8080/index 页面显示如下:
![](http://img.saoniuhuo.com/images/202108/42321629902606869.jpg)

相关文章

微信公众号

最新文章

更多