簡體   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