关注Java后端技术全栈”**

回复“面试”获取全套大厂面试材料

前言

  • Thymeleaf 是一个跟 Velocity、FreeMarker 相似的模板引擎,它能够齐全代替 JSP 。相较与其余的模板引擎,它有如下三个极吸引人的特点
  • Thymeleaf 在有网络和无网络的环境下皆可运行,即它能够让美工在浏览器查看页面的动态成果,也能够让程序员在服务器查看带数据的动静页面成果。这是因为它反对 html 原型,而后在 html 标签里减少额定
    的属性来达到模板 + 数据的展现形式。浏览器解释 html 时会疏忽未定义的标签属性,所以 thymeleaf 的模板能够动态地运行;当有数据返回到页面时,Thymeleaf 标签会动静地替换掉动态内容,使页面动态显示。
  • Thymeleaf 开箱即用的个性。它提供规范和 Spring 规范两种方言,能够间接套用模板实现 JSTL、 OGNL 表达式成果,防止每天套模板、改 JSTL、改标签的困扰。同时开发人员也能够扩大和创立自定义的方言。
  • Thymeleaf 提供 Spring 规范方言和一个与 SpringMVC 完满集成的可选模块,能够疾速的实现表单绑定、属性编辑器、国际化等性能。

Thymeleaf简述

Thymeleaf 是 Java 模板引擎,Spring 官网举荐应用,也是 Spring Boot 默认的模板引擎;前后端拆散之前就是thymeleaf这类引擎模板的地盘;其反对HTML5的视图模板,可能无缝连接springboot;主要用途能进行web开发和非web开发,比方页面渲染,代码生成,文档生成等等,做些日常的小工具是个很好的抉择;

开发传统Java WEB工程时,咱们能够应用JSP页面模板语言,然而在SpringBoot中曾经不举荐应用了。SpringBoot反对如下页面模板语言

  • Thymeleaf
  • FreeMarker
  • Velocity
  • Groovy
  • JSP

下面并没有列举所有SpringBoot反对的页面模板技术。其中Thymeleaf是SpringBoot官网所举荐应用的,上面来谈谈Thymeleaf一些罕用的语法规定。

增加依赖包

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

Spring Boot默认寄存模板页面的门路在

src/main/resources/templates或者src/main/view/templates,然而index.html默认是在static目录下。

这个无论是应用什么模板语言都一样,当然默认门路是能够自定义的,不过个别不举荐这样做。另外Thymeleaf默认的页面文件后缀是.html

application.properties增加配置项

#开启thymeleaf视图解析spring.thymeleaf.enabled=true#编码为UTF-8spring.thymeleaf.encoding=UTF-8#是否应用缓存(开发环境倡议应用false,线上应用true)spring.thymeleaf.cache=falsespring.resources.chain.strategy.content.enabled=truespring.resources.chain.strategy.content.paths=/**#严格执行HTML语法格局spring.thymeleaf.mode=HTML#模式spring.thymeleaf.servlet.content-type=text/html

在templates目录下创立hello.html,内容

<!DOCTYPE HTML><html xmlns:th="http://www.thymeleaf.org"><head>    <title>SpringBoot thymeleaf 模版渲染</title>    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/></head><body><p th:text="'用户ID:' + ${pwd}"/><p th:text="'用户名称:' + ${name}"/></body></html>

controller

@Controller@RequestMapping()public class ThymeleafController {    @RequestMapping(value = "hello", method = RequestMethod.GET)    public String show(Model model){        model.addAttribute("pwd","123456");        model.addAttribute("name","Java后端技术全栈");        return "hello";    }}

启动,拜访http://localhost:8080/hello

OK,自此Spring Boot 集成Thymeleaf入门搞定。

如果想深刻的理解Thmeleaf相干的,请关注官网

https://www.thymeleaf.org/doc...

Thymeleaf的demo案例(集成Spring 、Spring Security 3.x and 4.x)

https://github.com/thymeleaf

举荐浏览

恕我直言,HttpClient 你不肯定会用

MySQL查问优化实战篇