您的位置:首页 > 编程语言 > Java开发

SpringBoot 从零开始学习(七) 之视图层技术整合thymeleaf

2020-03-08 12:25 387 查看

1.在pom文件中添加thymeleaf启动器坐标:

<!-- themeleaf 启动器坐标 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2.业务类:

package com.cz.pojo;

public class User {

private int id;
private String name;
private int age;

public User() {
}

public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

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;
}

}

3.controller

package com.cz.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cz.pojo.User;
import com.sun.org.apache.bcel.internal.generic.NEW;

@Controller
public class ThymeleafController {

@RequestMapping("/showUser")
public String showUser(Model model) {

/*start 这里是传递list*/
List userList = new ArrayList<User>();
userList.add(new User(1, "张三", 20));
userList.add(new User(2,"李四",30));
userList.add(new User(44,"王五",40));
model.addAttribute("users", userList);
/*end 这里是传递list*/

/*start 这里是传递text*/
model.addAttribute("msg", "我们的祖国是花园");
/*end 这里是传递text*/

/*start 这里是传递date*/
model.addAttribute("date", new Date());
/*end 这里是传递date*/
return "showUser";
}
}

4.模版视图,放在src/main/resources/templates 该目录是安全的,不允许外界直接访问,必须通过controller 的进行视图定位跳转

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"> </meta>
<title>Thymeleaf project</title>
</head>
<body>
<span th:text="我的中国心!"></span>

<hr>

<span th:text="${msg}"></span>

<hr>

<table border="10" align="center" width="50%" >
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
</tr>

<tr th:each = "user:${users}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.age}"></td>
</tr>
</table>

<hr>
<span th:text="${date}"></span>
<hr>

</body>
</html>

5.执行效果图:

  • 点赞
  • 收藏
  • 分享
  • 文章举报
不二村长 发布了11 篇原创文章 · 获赞 0 · 访问量 154 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: