SpringBoot笔记(二)---- SpringBoot整合Thymeleaf模板

Thymeleaf是现在流行的模板引擎。在项目开发中,JSP作为前端界面渲染,不能做到现在所追求的前后端分离,所以很多人开始使用模板引擎。使用Thymeleaf最大的优势是后缀为html,再加上浏览器就可以展示页面了,还有一个重要的优势就是thymeleaf可以很好的和spring集成。

整合过程:

1.添加Thymeleaf支持(SpringBoot笔记(一)---- 入门笔记中pom文件的基础上添加)

<!--添加对templates模板的支持-->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

2.在resources文件夹下创建templates文件夹,用来放.html文件,在该文件夹下创建helloThy.html文件。注意:添加thymeleaf支持后在控制器方法中返回静态界面,spring boot会首先找resources下 templates中的.html件, 返回的jsp静态页面将不在生效。

3.在application.properties文件中添加如下配置关闭thymeleaf缓存,(不关闭也没有关系,当官方建议开发过程中关闭缓存)

       #页面热加载  开发过程建议关闭缓存

      spring.thymeleaf.cache = false    

4.在控制器中编写如下Controller:

       

5.编写跳转到的HTML文件,位置如下图所示:

6.HTML文件引入Thymeleaf模板引擎需要做一些改变,如下:

  a.替换头部信息

    <!DOCTYPE html>

    <html xmlns:th="www.thymeleaf.org" xmlns="http://www.w3.org/1999/xhtml">

  b.严格关闭标签,特别HTML中自动生成的link、meta、img等标签手动关闭
  c.替换路径。包括src,href,url等。(替换成Thymeleaf模板取值形式,具体见文章thymeleaf模板的传值取值)

7.HTML具体编写和取值如下

   

8.访问测试,结果如下:

 

猜你喜欢

转载自blog.csdn.net/qq_37918817/article/details/81780611