1 模板渲染
1.1 Spring boot通过thymeleaf引擎来对html页面进行渲染,简单说就是通过该引擎来动态地向html页面填充数据
1.2 使用thymeleaf必须在pom.xml添加spring-boot-starter-thymeleaf依赖如下
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
1.3 新建一个Blog类,如下
class Blog{
public String title;
public String content;
public Blog(String title, String content){
this.title = title;
this.content = content;
}
}
1.4 添加一个方法,如下
@RequestMapping("/getcontent")
public String getcontent(@RequestParam String id, Model m) {
Blog b = new Blog(id, id+"---"+id);
m.addAttribute("b", b);
return "blogContent";
}
1.5 Model m 为spring boot提供的一个像页面传递数据的对象类型,它封装了HttpRequest、HttpResponse、HttpSession等对象
1.6 Blog b 是我们要返回的数据对象,这里我们对他进行了实例化和初始化
1.7 m.addAttribute("b",b) 是将b对象存放到Model对象的“b”属性中去,这样我们就可以在页面中通过b来访问b对象
1.8 return "blogContent" 后程序会到/templates下寻找blogContent.html页面并进行渲染
1.9 在templates下建立页面blogContent.html,如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"></meta>
<title>Title</title>
</head>
<body>
<div class="col-sm-8">
<div class="page-header">
博客标题是:
<h2 th:text="${b.title}">Cum sociis(博客标题)</h2>
</div>
博客内容是:
<div class="blog-post-content" th:text="${b.content}">
...
(这里是博客内容)
</div>
</div>
</body>
</html>
1.10 通过th:text="${b.title}"我们将数据绑定到了<h2>标签中,它会替换现有的<h2>标签中的内容,而b就是我们在Model中添加的属性b
2 Thymeleaf模板引擎
Thymeleaf引擎最大的特点是通过标签属性渲染标签内容,如上面的例子,th:后接text就是渲染该标签的text内容
3 渲染url,如下,渲染前连接为http://baidu.com,渲染后链接为/blog/string
<a href="http://baidu.com" th:href="@{/blog/string}">to string page</a>
4 渲染循环,如下
//java代码
List<Blog>bs = new ArrayList<Blog>();
bs.add(new Blog(id,id+"---"+id));
bs.add(new Blog(id+id,id+"-----999"));
m.addAttribute("bs", bs);
//html页面绑定代码如下
循环绑定:
<div class="blog-post-content" th:each="b : ${bs}">
<div>
<span th:text="${b.title}">b.name</span>
<span th:text="${b.content}">b.content</span>
</div>
</div>
5 日期格式化,如下
//java代码
Date d = new Date();
m.addAttribute("d", d);
绑定日期:
<div th:text="${d}">日期</div>
日期格式化后:
<div th:text="${#dates.format(d, 'yyyy-MM-dd hh:mm:ss')}">日期</div>
<a href="http://baidu.com" th:href="@{'/blog/string'}">to string page</a>
直接${d}会调用Date的toString方法,要格式化需使用thymeleaf内置的#dates工具的format函数来实现
6 支持jsp模板引擎,暂时没有调通,搁置