SpringBoot提供了默认配置的模板引擎主要有以下几种:Thymeleaf、FreeMarker、Velocity、Groovy、Mustache
默认的创建SpringBoot项目时,开发工具就帮我们创建好了src/main/resources/static目录,该位置存放常用的静态资源,如js、css、图片等。src/main/resources/templates 存放模板文件。
1、thymeleaf
Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发,它是一个开源的Java库。
示例:
在pom.xml 中添加 thymeleaf 依赖,如果之前没有 web 依赖也一起添加,然后重新加载 jar 依赖:
<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>
在 src/main/resources/templates 目录下创建 myIndex.html 文件
内容如下:注意 thymeleaf 的语法。如果想接触 thymeleaf ,可以参考简书的:Thymeleaf 简易教程
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SpringBoot测试thymeleaf模板</title>
</head>
<body>
用户:<h2 th:text="${name}"></h2>
描述:<h2 th:text="${desc}"></h2>
</body>
</html>
编写 ThymeleafController java类:
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
@Controller //不是使用 ResController
public class ThymeleafController {
@RequestMapping("/thy")
public String thymeleaf(ModelMap map){
map.addAttribute("name","流放深圳");
map.addAttribute("desc","让天下没有难写的代码");
return "myIndex";//返回的是html的文件名
}
}
启动服务,浏览器地址访问(根据自己配置的端口号来访问):http://localhost:9090/thy
说明:如果需要修改 html的内容,也需要重新服务,因为 thymeleaf 是需要编译的。
2、freeMarker
在pom.xml 配置文件中添加如下配置,然后重新加载 jar 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
在 src/main/resources/templates 目录下创建 myFreeMarker.ftl 文件 (技巧:先创建 html 文件,再重命名 .ftl)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SpringBoot测试freeMarker模板</title>
</head>
<body>
<h2>${name}</h2>
<h2>${desc}</h2>
</body>
</html>
然后编写 FreeMarkerController 类(实际上跟ThymeleafController 代码一样,为了学习,最好有明显的区分。如 url 映射)
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
@Controller //不是使用 ResController
public class FreeMarkerController {
@RequestMapping("/free")
public String thymeleaf(ModelMap map){
map.addAttribute("name","流放深圳");
map.addAttribute("desc","让天下没有难写的代码");
return "myFreeMarker";//返回的是html的文件名
}
}
启动服务,浏览器地址访问(根据自己配置的端口号来访问):http://localhost:9090/free