springboot对Thymeleaf模板引擎的支持

Thymeleaf对比jsp最大的优势在于:

    它是静态的html资源,不需要进行编译成servlet运行在tomcat服务器上,前端ui可以在其上直接进行美工

开始集成Thymeleaf
  第一步:引入依赖(thymeleaf对应的starter),IDEA创建springboot模板时可以在可视化向导中勾选
    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
  第二步:配置thymeleaf,这里使用的是在application.properties中配置

    #指定模板所在的目录
    spring.thymeleaf.classpath=/templates/
    #检查模板路径是否存在
    spring.thymeleaf.check-template-location=true
    #是否缓存,开发模式下设置为false,避免改了模板还要重启服务器,线上设置为true,可以提高性能。
    spring.thymeleaf.cache=false
    #模板文件后缀名
    spring.thymeleaf.suffix= .html
    #编码格式
    spring.thymeleaf.encoding=UTF-8
    #content-typespring.thymeleaf.servlet.content-type=text/html#spring.thymeleaf.mode的默认值是HTML5,其实是一个很严格的检查,改为LEGACYHTML5可以得到一个可能更友好亲切的格式要求。#比如你在使用Vue.js这样的库,然后有<div v-cloak></div>这样的html代码,也被thymeleaf认为不符合要求而抛出错误。
    spring.thymeleaf.mode = LEGACYHTML5

  第三步:创建一个控制器,控制器这里必须采用@Controller进行注解,千万不要使用@RestController
    @Controller

    public class UserController {
      /*** 采用model往request域中存值,存入2个普通的字符串
      * @param model
      * @return
      */
      @GetMapping("/userinfo1")
      publicStringuserinfo1(Modelmodel) {
        Stringusername="xiadewang";
        Stringpassword="123456";
        model.addAttribute("username", username);
        model.addAttribute("password", password);return"userinfo1";
      }
    }

    这里我们使用了@GetMapping注解,它相当于是它的一个简化版写法。在springboot中跳转模板页,统一将方法返回值设置为String即可,返回给模板引擎的数据可以通过在方法中加入形参Model来进行存储。我们之前已经配置了模板引擎的前缀和后缀,我们在这里的返回值只用设置为模板页
    
  第四步::在模板引擎配置的模板路径下创建模板页面,此处我们在Templete下创建一个userinfo1.html页面:在模板引擎配置的模板路径下创建模板页面,此处我们在Templete下创建一个userinfo1.html页
 

<!DOCTYPE html>
<htmllang="en"xmlns:th="http://www.thymeleaf.org">
<head>
<metacharset="UTF-8">
<title>Title</title>
</head>
<body>
<pth:text="'用户名:'+${username}"></p>
<pth:text="'密码:'+${password}"></p>
</body>
</html>

此处在html上加入了一个命名空间xmlns:th="http://www.thymeleaf.org",代表可以用来引入thymeleaf的标签库,下面利用th标签和el表达式来获取后端传递过
 
注意:
  可以采用model往request域中存值(集合,对象,属性)
  模板引擎的作用都是将模板(页面)和数据进行整合然后输出显示,区别在于不同的模板使用不同的语法,如 JSP 的 JSTL 表达式,以及 JSP 自己的表达式和语法,同理 Thymeleaf 也有自己的语法