Spring Boot Thymeleaf CRUD快速入门教程
1.简介
Thymeleaf是一个Java模板引擎,用于处理和创建HTML,XML,JavaScript,CSS和文本。
该库具有极强的可扩展性,其自然的模板功能可确保无需后端即可对模板进行原型制作-与其他流行的模板引擎(如JSP)相比,开发速度非常快。
2. Thymeleaf与Spring Boot集成
首先让我们看看与Spring集成所需的配置。该thymeleaf弹簧库是必需的集成。
将以下依赖项添加到您的Maven POM文件中:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.kongliand</groupId> <artifactId>springboot-thymeleaf</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot-thymeleaf</name> <description>springboot-thymeleaf</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.22</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
3.服务接口
package com.kongliand.thymeleaf.repository; import com.kongliand.thymeleaf.entity.User; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends CrudRepository<User, Long> {}
4.用户实体类
package com.kongliand.thymeleaf.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String name; private String 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; } }
5.用户接口访问入口
package com.kongliand.thymeleaf.controller; import com.kongliand.thymeleaf.entity.User; import com.kongliand.thymeleaf.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; /*** * @author kevin * @date 2020/08/04 * @version 1.0 */ @Controller public class UserController { @Autowired private UserRepository userRepository; @GetMapping("/signup") public String showSignUpForm(User user) { return "add-user"; } @PostMapping("/adduser") public String addUser(User user, BindingResult result, Model model) { if (result.hasErrors()) { return "add-user"; } userRepository.save(user); model.addAttribute("users", userRepository.findAll()); return "redirect:/index"; } @GetMapping("/edit/{id}") public String showUpdateForm(@PathVariable("id") long id, Model model) { User user = userRepository.findById(id) .orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id)); model.addAttribute("user", user); return "update-user"; } @PostMapping("/update/{id}") public String updateUser(@PathVariable("id") long id, User user, BindingResult result, Model model) { if (result.hasErrors()) { user.setId(id); return "update-user"; } userRepository.save(user); model.addAttribute("users", userRepository.findAll()); return "redirect:/index"; } @GetMapping("/delete/{id}") public String deleteUser(@PathVariable("id") long id, Model model) { User user = userRepository.findById(id) .orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id)); userRepository.delete(user); model.addAttribute("users", userRepository.findAll()); return "index"; } @GetMapping("/index") public String index(Model model) { model.addAttribute("users", userRepository.findAll()); return "index"; } }
5.前端操作页面
-
5.1 列表面
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div th:switch="${users}"> <h2 th:case="null">No users yet!</h2> <div th:case="*"> <h2>Users</h2> <table> <thead> <tr> <th>Name</th> <th>Email</th> <th>Edit</th> <th>Delete</th> </tr> </thead> <tbody> <tr th:each="user : ${users}"> <td th:text="${user.name}"></td> <td th:text="${user.email}"></td> <td><a th:href="@{/edit/{id}(id=${user.id})}">Edit</a></td> <td><a th:href="@{/delete/{id}(id=${user.id})}">Delete</a></td> </tr> </tbody> </table> </div> <p><a href="/signup">Add a new user</a></p> </div> </body> </html>
-
5.2 添加面
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="#" th:action="@{/adduser}" th:object="${user}" method="post"> <label for="name">Name</label> <input type="text" th:field="*{name}" id="name" placeholder="Name"> <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></span> <label for="email">Email</label> <input type="text" th:field="*{email}" id="email" placeholder="Email"> <span th:if="${#fields.hasErrors('email')}" th:errors="*{email}"></span> <input type="submit" value="Add User"> </form> </body> </html>
-
5.3 修改面
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="#" th:action="@{/update/{id}(id=${user.id})}" th:object="${user}" method="post"> <label for="name">Name</label> <input type="text" th:field="*{name}" id="name" placeholder="Name"> <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></span> <label for="email">Email</label> <input type="text" th:field="*{email}" id="email" placeholder="Email"> <span th:if="${#fields.hasErrors('email')}" th:errors="*{email}"></span> <input type="submit" value="Update User"> </form> </body> </html>
- 最后测试一下