Thymeleaf与Spring Boot集成,实战

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40132006/article/details/81504649

1.build.gradle

dependencies{
       //添加Thymeleaf
	compile('org.springframework.boot:spring-boot-starter-thymeleaf')

}

spring-boot-starter-thymeleaf库默认使用的是最新版本的,主要依赖以下三个库:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring5</artifactId>
    </dependency>

    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-java8time</artifactId>
    </dependency>


</dependencies>

自定义版本

buildscript {
	ext['thymeleaf.version'] = '3.0.3.RELEASE'
	ext['thymeleaf-layout-dialect.version'] = '2.2.0'
}

2.修改application.properties

application.properties 文件在Spring Boot项目中是用于配置项目的配置文件,需在添加以下几项

# Thymeleaf编码
spring.thymeleaf.encoding=UTF-8
# 热部署静态文件,指不对Thymeleaf模板进行缓存,
# 这样在开发阶段修改模板后,就能在浏览器中及时看到修改后页面效果
spring.thymeleaf.cache=false
# 使用HTML5标准
spring.thymeleaf.mode=HTML5

3.在项目的domain包下创建User.java


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {
	
	@Id//主键
	@GeneratedValue(strategy=GenerationType.IDENTITY)// 自增长
	private Long id;
	private String name;
	private String email;
	public User() {//无参构造函数
	}
	public User(Long id,String name,String email){
		this.id = id;
		this.name = name;
		this.email = email;
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", email=" + email + "]";
	}
}

4.创建资源库

在Repository包下创建UserRepository接口


import java.util.List;


public interface UserRepository {
	/**
	 * 新增或修改用户
	 * @param user
	 * @return
	 */
	User saveOrUpdateUser(User user);
	/**
	 * 废除用户
	 * @param id
	 */
	void deleteUser(Long id);
	/**
	 * 根据用户id获取用户
	 * @param id
	 * @return
	 */
	User getUserById(Long id);
	/**
	 * 获取所有用户的列表
	 * @return
	 */
	List<User> listUser();
}

并创建UserRepositoryImpl类作为实现类



import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;

import org.springframework.stereotype.Repository;
import org.w3c.dom.css.Counter;

//标识一个可注入的bean
@Repository
public class UserRepositoryImpl implements UserRepository{
	
	//产生一个递增的id
	private static AtomicLong Counter = new AtomicLong();
	//模拟数据存储
	private final ConcurrentMap<Long, User> userMap = new ConcurrentHashMap<Long,User>();

	@Override
	public User saveOrUpdateUser(User user) {
		Long id = user.getId();
		if(id == null) {
			id = Counter.incrementAndGet();
			user.setId(id);
		}
		this.userMap.put(id, user);
		return user;
	}

	@Override
	public void deleteUser(Long id) {
		this.userMap.remove(id);
	}

	@Override
	public User getUserById(Long id) {
		return this.userMap.get(id);
	}

	@Override
	public List<User> listUser() {
		return new ArrayList<User>(this.userMap.values());
	}

}

5.修改控制器

在项目下创建controller包并建立UserController用于处理界面的请求.



import org.h2.util.New;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;


@RestController
@RequestMapping("/users")
public class UserController {

	@Autowired
	private UserRepository userRepository;
	/**
	 * 查询所有用户
	 * @param model
	 * @return
	 */
	@GetMapping
	public ModelAndView list(Model model) {
		model.addAttribute("userList",userRepository.listUser());
		model.addAttribute("title","用户管理");
		return new ModelAndView("users/list","userModel",model);	
	}
	/**
	 * 根据id查询用户
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("{id}")
	public ModelAndView view(@PathVariable("id") Long id,Model model) {
		User user = userRepository.getUserById(id);
		model.addAttribute("user",user);
		model.addAttribute("title","查看用户");
		return new ModelAndView("users/view","userModel",model);
	}
	/**
	 * 获取创建表单页面
	 * @param model
	 * @return
	 */
	@GetMapping("/form")
	public ModelAndView createForm(Model model) {
		model.addAttribute("user", new User());
		model.addAttribute("title","创建用户");
		return new ModelAndView("users/form","userModel",model);
	}
	/**
	 * 保存用户
	 * @param user
	 * @return
	 */
	@PostMapping
	public ModelAndView saveOrUpdateUser(User user) {
		user = userRepository.saveOrUpdateUser(user);
		return new ModelAndView("redirect:/users");
	}
	/**
	 * 废除用户
	 * @param id
	 * @return
	 */
	@GetMapping(value = "delete/{id}")
	public ModelAndView delete(@PathVariable("id") Long id) {
		userRepository.deleteUser(id);
		return new ModelAndView("redirect:/users");
	}
	/**
	 * 获取修改用户的界面
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping(value = "modify/{id}")
	public ModelAndView modifyForm(@PathVariable("id") Long id,Model model) {
		User user = userRepository.getUserById(id);	
		model.addAttribute("user",user);
		model.addAttribute("title","修改用户");
		return new ModelAndView("users/form","userModel",model);
	}
	
	
}

 6.在项目的templates目录下新建一个fragments页面,来归档页面共用的部分

包括:list.html 展现用户列表,form.html 用于新增或修改用户的资料,view.html 用于查看某个用户的资料,

新建一个fragments页面,来归档页面公用部分

包括:header.html 为共用的头部页面;footer.html 为共用的底部页面.以下是完整代码:

a.list.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" 
	xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">

<head>
	<meta charset="UTF-8">
	<title>Thymeleaf in action</title>
</head>

<body>
	<div th:replace="~{fragments/header :: header}"></div>
	<h3 th:text="${userModel.title}">waylau</h3>
	<div>
		<a href="/users/form.html" th:href="@{/users/form}">创建用户</a>
	</div>
	<table border="1">
		<thead>
			<tr>
				<td>ID</td>
				<td>Email</td>
				<td>Name</td>
			</tr>
		</thead>
		<tbody>
			<tr th:if="${userModel.userList.size()} eq 0">
				<td colspan="3">没有用户信息!</td>
			</tr>
			<tr th:each="user : ${userModel.userList}">
				<td th:text="${user.id}"></td>
				<td th:text="${user.email}"></td>
				<td><a th:href="@{'/users/'+${user.id}}" th:text="${user.name}"></a></td>
			</tr>
		</tbody>
	</table>
	<div th:replace="~{fragments/footer :: footer}"></div>
</body>

</html>

b.form.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" 
	xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">

<head>
	<meta charset="UTF-8">
	<title>Thymeleaf in action</title>
</head>

<body>
	<div th:replace="~{fragments/header :: header}"></div>
	<h3 th:text="${userModel.title}">waylau</h3>
	<form action="/users" th:action="@{/users}" method="POST" th:object="${userModel.user}">
		<input type="hidden" name="id" th:value="*{id}"> 名称:
		<br>
		<input type="text" name="name" th:value="*{name}">
		<br> 邮箱:
		<br>
		<input type="text" name="email" th:value="*{email}">
		<input type="submit" value="提交">
	</form>
	<div th:replace="~{fragments/footer :: footer}"></div>
</body>

</html>

c.view.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" 
	xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">

<head>
	<meta charset="UTF-8">
	<title>Thymeleaf in action</title>
</head>

<body>
	<div th:replace="~{fragments/header :: header}"></div>
	<h3 th:text="${userModel.title}">waylau</h3>
	<div>
		<P><strong>ID:</strong><span th:text="${userModel.user.id}"></span></P>
		<P><strong>Name:</strong><span th:text="${userModel.user.name}"></span></P>
		<P><strong>Email:</strong><span th:text="${userModel.user.email}"></span></P>
	</div>
	<div>
		<a th:href="@{'/users/delete/'+${userModel.user.id}}">删除</a>
		<a th:href="@{'/users/modify/'+${userModel.user.id}}">修改</a>
	</div>
	<div th:replace="~{fragments/footer :: footer}"></div>
</body>

</html>

d.header.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" 
	xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">

<head>
	<meta charset="UTF-8">
	<title>Thymeleaf in action</title>
</head>

<body>
	<div th:fragment="header">
		<h1>Thymeleaf in action</h1>
		<a href="/users" th:href="@{~/users}">首页</a>
	</div>
</body>

</html>

e.footer.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" 
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">

<head>
      <meta charset="UTF-8">
      <title>Thymeleaf in action</title>
</head>

<body>
      <div th:fragment="footer">
            <a href="https://waylau.com">Welcome to waylau.com</a>
      </div>
</body>

</html>

7.运行测试

猜你喜欢

转载自blog.csdn.net/weixin_40132006/article/details/81504649