SpringBoot+Thymeleaf(入门)

SpringBoot+Thymeleaf(入门)


Thymeleaf 介绍

简单说,Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP。

  • 它可以在浏览器查看页面的静态效果,也可以在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
  • Thymeleaf 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
  • Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

使用

① pom.xml添加依赖
//构建 Web 应用
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.1.3.RELEASE</version>
</dependency>

//thymeleaf 模板
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>2.1.3.RELEASE</version>
</dependency>
②在application.properties中添加配置
//文档类型
spring.thymeleaf.servlet.content-type=text/html
//模块编码
spring.thymeleaf.mode=HTML
//是否开启缓存
spring.thymeleaf.cache=false
③编写测试Controller类
@Controller
public class TestController {
    @RequestMapping("/test")
    public ModelAndView test(ModelAndView modelAndView) {
        modelAndView.addObject("hello","这是我第一个使用Thymelead的页面!");
        modelAndView.setViewName("test");
        return modelAndView;
    }
}
④编写html页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div th:text="${hello}">文本内容</div>
</body>
</html>
⑤运行

在这里插入图片描述


补充:thymeleaf模板配置项

参数 介绍
spring.thymeleaf.cache = true 启用模板缓存(开发时建议关闭)
spring.thymeleaf.check-template = true 检查模板是否存在,然后再呈现
spring.thymeleaf.check-template-location = true 检查模板位置是否存在
spring.thymeleaf.content-type = text/html Content-Type值
spring.thymeleaf.enabled = true 启用MVC Thymeleaf视图分辨率
spring.thymeleaf.encoding = UTF-8 模板编码
spring.thymeleaf.excluded-view-names = 应该从解决方案中排除的视图名称的逗号分隔列表
spring.thymeleaf.mode = HTML5 应用于模板的模板模式
spring.thymeleaf.prefix = classpath:/templates/ 在构建URL时预先查看名称的前缀
spring.thymeleaf.suffix = .html 构建URL时附加查看名称的后缀
spring.thymeleaf.template-resolver-order = 链中模板解析器的顺序
spring.thymeleaf.view-names = 可以解析的视图名称的逗号分隔列表

猜你喜欢

转载自blog.csdn.net/weixin_42909660/article/details/88852761