繁体   English   中英

我如何以单一形式通过两个:object

[英]How do i pass two th:object in a single form

我是 thymeleaf 的新手,找不到以单个 HTML 形式传递两个对象的方法。 如何传递两个不同的实体对象。在这种情况下,我的实体是 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>

这是我的 controller,它是原始的。

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

谢谢。

您创建一个包含PatientDoctor的新 object 。

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>

ETC...

使用映射到表单数据中的字段的专用数据传输 Object 可能会更好:

public class LoginFormData {
  private String email;
  private String password;
}

然后从PatientDoctor实体转换为LoginFormData并返回 controller。

边注:

  • 如果打算使用表单更改数据,请在表单中使用th:method="post"@PostMapping中的 @PostMapping
  • 拥有一个方法findByeMailAndPassword不是您应该拥有的。 密码应该以纯文本形式存在于数据库中,尝试使用其纯文本密码查找某个用户会很奇怪。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM