我是新手,无法找到在单个HTML表单中传递两个th:对象的方法。我如何传递两个不同的实体对象。在本例中,我的实体是Patient和Doctor。我的表格如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<title>LOG IN PAGE</title>
</head>
<body>
<div class="container">
<form th:action="@{/loggedProfile}" th:object="${patient,doctor}"
method="get">
<div class="form-group">
<label for="patientEmail">Email address</label> <input type="email"
class="form-control" placeholder="Enter Your email"
th:field="*{eMail}"> <small id="emailHelp"
class="form-text text-muted">We'll never share your email
with anyone else.</small>
</div>
<div class="form-group">
<label for="patientPassword">Password</label> <input type="password"
class="form-control" placeholder="Enter Your Password"
th:field="*{password}">
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</body>
<div th:insert="Header-Footer/common_header_footer"></div>
</html>
这是我的控制器,它是raw。
@GetMapping("/logIn")
public String logIn(Model model) {
Patient patient = new Patient();
model.addAttribute("patient", patient);
Doctor doctor = new Doctor();
model.addAttribute("doctor", doctor);
return "UI-Pages/LogIn_Page";
}
@GetMapping("/loggedProfile")
public String loggedProfile(@ModelAttribute Doctor doctor,@ModelAttribute Patient patient,Model model) {
doctor = docRep.findByeMailAndPassword(doctor.geteMail(), doctor.getPassword());
patient = patRep.findByeMailAndPassword(patient.geteMail(), patient.getPassword());
model.addAttribute("doctor", doctor);
model.addAttribute("patient", patient);
return "Profile-Pages/Patient_Profile";
}
谢谢。
创建一个包含Patient
和Doctor
的新对象。
public class LoginForm {
private Patient patient;
private Doctor doctor;
// getters and setters
}
然后像这样访问这些字段:
<form th:action="@{/loggedProfile}" th:object="${form}"
th:field="*{patient.eMail}"
....
th:field="*{doctor.password}"
</form>
等等……
最好使用专用的Data Transfer Object来映射到表单Data中的字段:
public class LoginFormData {
private String email;
private String password;
}
然后从Patient
或Doctor
实体转换为LoginFormData
并返回控制器。
注:
- 如果想使用表单更改数据,则在表单中使用
th:method="post"
,在控制器中使用@PostMapping
- 有一个方法
findByeMailAndPassword
不是你应该有的东西。密码应该以明文形式存在于数据库中,如果试图用明文密码找到某个用户,那就太奇怪了。