SpringBoot 集成Thymeleaf模板引擎
SpringBoot支持的模板引擎:Thymeleaf、Velocity、FreeMarker等。SpringBoot默认的模板引擎路径是:src/main/resources/templates。
SpringBoot+Thymeleaf 集成开发
第一步:引入thymeleaf的依赖:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.zzg</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>Thymeleaf</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- thymeleaf依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
</project>
编写Thymeleaf关联的Controller:
package com.springboot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = "/thymeleaf")
public class ThymeleafController {
@RequestMapping("/web")
public String hello(ModelMap modelMap) {
// 向模板中添加属性
modelMap.put("thymeleaf", "Thymeleaf模板引擎");
// return模板文件的名称,对应src/main/resources/templates/index.html
return "index";
}
}
编写模板:
在src/main/resources/templates 文件夹中创建index.html 模板文件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<body>
<h1 th:text="${thymeleaf}">Thymeleaf模板引擎</h1>
</body>
</html>
Thymeleaf 相关配置,此处以application.yml文件。
spring:
thymeleaf:
cache: true
check-template-location: true
content-type: text/html
enabled: true
encoding: utf-8
mode: HTML5
prefix: classpath:/templates/
suffix: .html
excluded-view-names:
template-resolver-order:
SpringBoot 程序入口
package com.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ThymeleafSpringBoot {
public static void main(String[] args) {
// TODO Auto-generated method stub
SpringApplication.run(ThymeleafSpringBoot.class, args);
}
}
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。