我有一个简单的thymeleaf用户注册页面。我有一个实体存储的形式数据休眠。这里是thymeleaf页面
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Customer Registration</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
<section>
<div>
<div>
<div>
<div>
<p>Sign up</p>
<form th:action="@{/register}" method="post" th:object="${employee}">
<div>
<input type="text" class="form-control" id="firstName" name="firstName" required placeholder="First Name">
</div>
<div>
<input type="text" class="form-control" id="LastName" name="lastName" required placeholder="Last Name">
</div>
<div>
<input type="email" class="form-control" id="email" name="email" required placeholder="Email">
</div>
<div>
<input type="tel" class="form-control" id="phoneNumber" name="phoneNumber" required placeholder="Mobile">
</div>
<div>
<input type="password" class="form-control" id="password" name="password" required placeholder="Password">
</div>
<div>
<input type="password" class="form-control" id="confirmPassword" name="confirmPassword" required placeholder="Confirm Password">
</div>
<div>
<label>Role:</label>
<input type="radio" th:field="*{email}" th:value="admin" /> Admin
<input type="radio" th:field="*{email}" th:value="employee" /> Employee
</div>
<div>
<button type="submit" class="btn btn-primary btn-lg">Register</button>
</div>
</form>
</div>
<div>
<img src="https://mdbcdn.b-cdn.net/img/Photos/new-templates/bootstrap-registration/draw1.webp"
class="img-fluid" alt="Sample image">
</div>
</div>
</div>
</div>
</section>
<script src="https://kit.fontawesome.com/309181c27b.js" crossorigin="anonymous"></script>
</body>
</html>
字符串
在我看到的大多数博客中,他们都使用th:field="*{field name}"。但在我的例子中,我没有使用它,而是使用了name属性来匹配实体类中的字段名。我的问题是它是如何工作的?
实体类
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "employee_id")
private Long employeeId;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email")
private String email;
型
我想知道数据是如何绑定的,即使我没有遵循语法。
1条答案
按热度按时间x7rlezfr1#
th:field
设置字段的name
、value
和id
。实际上,您通过手动设置字段上的id
和name
来完成th:field
的部分工作。至于它是如何工作的,Spring只是将字段
name
s匹配到@ModelAttribute
上的属性-它不关心字段的name
是由Thymeleaf还是常规HTML属性设置的。