1.首先我们来介绍springboot推荐的视图模板thymeleaf。
thymeleaf的特点语法清晰,速度也不算很慢,那么spring用它作为默认视图模板也有一定的因素,但是目前还不得而知,据说新版本渲染速度有一定提升,但是没经过数据检验,大家喜欢可以去研究一下。今天我们来简单介绍一下。
首先在application.properties里做配置。
#thymelea模板配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
#可不选择
spring.thymeleaf.encoding=UTF-8
#热部署文件,页面不产生缓存,及时更新
spring.thymeleaf.cache=false
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
其次我们新建一个ThymeleafController ,来测试一波。
package yick.demo.springboot;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
@RestController
@RequestMapping(value = "view")
public class ThymeleafController {
@GetMapping(value = "list")
public ModelAndView list(Model model) {
User user = new User("1", "易先生", 28);
model.addAttribute("title", "用户管理");
model.addAttribute("user", user);
return new ModelAndView("users/view", "userModel", model);
}
}
User类型
package yick.demo.springboot;
public class User {
private String name;
private Integer age;
private String id;
public User() {
}
public User(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
view.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" >
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3 th:text="${userModel.title}">Welcome to springboot</h3>
<div>
<p><strong>ID:</strong><span id="id" th:text="${userModel.user.id}"></span></p>
<p><strong>Age:</strong><span id="id" th:text="${userModel.user.age}"></span></p>
<p><strong>Name:</strong><span id="id" th:text="${userModel.user.name}"></span></p>
</div>
<div>
<a th:href="@{'/users/delete/' + ${userModel.user.id} }">删除</a>
<a th:href="@{'/users/modify/' + ${userModel.user.id} }">修改</a>
</div>
</body>
</html>
来看看我们测试效果,访问http://localhost:8080/view/list

image.png
大功告成,thymeleaf视图就这么简单,详细语法可以自己研究或者继续关注我哦。

有你的支持,我会更努力哦!!!.jpg