版权声明:本文为博主原创文章,未经博主允许不得转载。https://blog.csdn.net/cms18374672699/article/details/87633805
史上最简单Spring Boot教程:第三篇SpringBoot之Thymeleaf模板(三)
转载请标明出处:https://blog.csdn.net/cms18374672699/article/details/87633805
Thymeleaf最大的优势后缀为html,就是只需要浏览器就可以展现页面了,还有就是thymeleaf可以很好的和spring集成。
一、引入依赖
在pom.xml文件中引入相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
二、配置视图解析器
spring-boot很多配置都有默认配置,比如默认页面映射路径为
classpath:/templates/*.html
同样静态文件路径为
classpath:/static/
在application.properties中可以配置thymeleaf模板解析器属性.就像使用springMVC的JSP解析器配置一样
spring: thymeleaf: cache: false freemarker: # 设置模板后缀名 suffix: .ftl # 设置文档类型 content-type: text/html # 设置页面编码格式 charset: UTF-8 # 设置页面缓存 cache: false # 设置ftl文件路径,默认是/templates,为演示效果添加role template-loader-path: classpath:/templates/role mvc: static-path-pattern: /static/**
三、编写后台代码
创建User实体类
package com.example.springboot02.entiry;
/**
* @author 清风半夜鸣蝉
* @site www.xiaomage.com
* @company xxx公司
* @create 2019-02-17 16:57
*/
public class User {
private int uid;
private String userName;
private String desc;
public User() {
}
public User(int uid, String userName, String desc) {
this.uid = uid;
this.userName = userName;
this.desc = desc;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
编写controller类
@Controller
public class IndexController {
@RequestMapping("/user/list")
public ModelAndView list(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("user/list");
modelAndView.addObject("title","用户列表");
List list = new ArrayList<>();
list.add(new User(1,"欧巴","沉默是金"));
list.add(new User(2,"激动","你看见啥了"));
modelAndView.addObject("users",list);
return modelAndView;
}
}
编写list.html静态页面
<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
</head>
<body>
<h1 th:text="${title}"></h1>
<table border="1px" width="600px">
<thead>
<tr>
<td>用户编号</td>
<td>用户姓名</td>
<td>用户描述</td>
</tr>
</thead>
<tbody>
<tr th:each="user:${users}">
<td th:text="${user.uid}"></td>
<td th:text="${user.userName}"></td>
<td th:text="${user.desc}"></td>
</tr>
</tbody>
</table>
<select>
<option>---请选择---</option>
<option th:each="user:${users}" th:value="${user.uid}" th:text="${user.userName}"></option>
</select>
</body>
</html>
在编写html页面时,引入thymeleaf的一个库,没有引入thymeleaf库编写th的时候是没有提示的
这样的话才可以在其他标签里面使用th:*
这样的语法
<html xmlns:th="http://www.thymeleaf.org">