在Springboot中,推荐使用的view是Thymeleaf,而不是jsp。尽管身为Java程序员,对jsp有着非常深厚的感情,但现在不得不赶紧学习Thymeleaf了。
本次实验使用了Thymeleaf的简单标签,进行入门。
首先导入Thymeleaf的依赖:
<!--导入html依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
application.properties中加入相关配置:
#thymeleaf start
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
#thymeleaf end
一个普通的JavaBean:
package com.example.demo.dao;
public class Person {
private String name;
private Integer 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 Person() {
super();
}
public Person(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
}
编写Controller,将我们需要展示到前端的对象存到Model中,前端便可以动态取用:
这里我们把一个List和一个Person对象加到了Model中
package com.example.demo.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.demo.dao.Person;
@Controller
public class LoginController {
@RequestMapping(value="/index")
public String index(Model model) {
Person single = new Person("张伟", 27);
List<Person> list = new ArrayList<Person>();
list.add(new Person("曾小贤", 26));
list.add(new Person("胡一菲", 22));
list.add(new Person("吕子乔", 24));
model.addAttribute("single", single);
model.addAttribute("peopleList", list);
return "index";
}
}
接下来编写前端展示页面,因为html是静态的,不能动态取数据,所以以前我们用的是jsp来配合后端。现在在Springboot中我们用Thymeleaf。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index.html</title>
</head>
<body>
<!-- 输出peopleList -->
<div th:if="${peopleList != null}">
<ul th:each="person:${peopleList}">
<li th:text="${person.name}"></li>
</ul>
</div>
<!-- 输出Model对象中的single属性 -->
<div th:if="${single != null}">
<p th:text="单身狗的人是: + ${single.name}">
<p th:text="年龄为 + ${single.age}">
</div>
</body>
</html>
Thymeleaf总体来讲,和html差别不大。它的特点是,动态的地方要用 th 标签属性
这里我们先对peopleList进行一个非空的判断,用th:if
标签,然后采用类似EL表达式的th:each标签,循环添加到一个无序列表中。
之后,我们用同样的方法,把single对象从Model中取了出来,然后直接显示到前端去。整个过程是一个动态的,因为渲染的内容是和后端程序有关的。
运行结果: