spring boot整合Thymeleaf模板
在SpringBoot使用Thymeleaf、FreeMarker、Mustache、Velocity模板,默认从 src/main/resources/templates 下加载。
- 支持无网络环境下运行,由于支持 html 原型,然后在 html 标签里增加额外的属性,来达到模板+数据的展示方式。浏览器解释 html 时,会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
- 开箱即用,为
Spring提供方言,可直接套用模板实现JSTL、 OGNL表达式效果,避免每天因套用模板而修改JSTL、 OGNL标签的困扰。同时开发人员可以扩展自定义的方言。 SpringBoot官方推荐模板,提供可选集成模块(spring-boot-starter-thymeleaf),可以快速的实现表单绑定、属性编辑器、国际化等功能。
首先要在 pom.xml 中添加对 thymeleaf 模板依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
@RequestMapping(method = RequestMethod.XXX)的写法,故而将其做一层包装,也就是现在的GetMapping、PostMapping、PutMapping、DeleteMapping、PatchMapping
package com.smart.boot_mybatis.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class ThymeleafController { @GetMapping("/index") public ModelAndView index(){ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("index"); modelAndView.addObject("title","音乐之声"); modelAndView.addObject("desc","音乐达人"); Singer singer = new Singer(); singer.setName("刘若英"); singer.setAge(30); modelAndView.addObject("singer",singer); return modelAndView; } private class Singer { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } }
在 src/main/resources/templates 目录下创建一个名 index.html 的模板文件,可以看到 thymeleaf 是通过在标签中添加额外属性动态绑定数据的
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title th:text="${title}">Title</title> </head> <body> <h2 th:text="${desc}">Hi</h2> <p th:text="${singer.name}"></p> <p th:text="${singer.age}"></p> </body>
为了提高响应速度,默认情况下会缓存模板。如果是在开发中请 将spring.thymeleaf.cache 属性设置成 false。在每次修改静态内容时 按Ctrl+Shift+F9 即可重新加载
立志如山 静心求实
浙公网安备 33010602011771号