Search code examples
htmlspringspring-bootspring-mvcthymeleaf

How do i pass two objects from thymeleaf form to Spring Controller?


I want to pass two objects from thymeleaf form to a controller. Here is my thymeleaf code :

<!DOCTYPE html>
<html lang='en' xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1"/>
<title>Payment Page</title>
</head>
<body>
<h1>Payment List</h1>

<table>
<tr>
 <th>StuId</th>
 <th>Month</th>
 <th>Amount</th>
 
</tr>
<tr th:each="payment:${student.payments}">
<td th:text="${student.id}">2</td>
<td th:text="${payment.month}">devesh</td>
<td th:text="${payment.amount}">23</td>
</tr>
</table>

<h3>Add a Payment</h3>
 <form action="#" th:action= "@{/payments}" th:object="${payment}" method="POST"> 
      <div th:object="${student}" >
 <label for="name">Month:</label>
   <input type="text" name="month" size="50"></input><br/> 
 <label for="amount">Amount:</label> 
   <input type="text" name="amount" size="50"></input><br/>
<input type = "submit"/></form>

</body>
</html>

in form except the payment object which is actually being submitted here , i want to pass student object or id to my controller as any payment should correspond to a particular student. i Could not find any way till now after searching a lot.

PaymentController method where i want to pass the objects , as i am using submit form , i could not pass variable in th:action

@RequestMapping(method = RequestMethod.POST, value = "/{id}/payments")
    public String doPayment(@ModelAttribute("payment") PaymentRecord paymentRecord, @PathVariable int id) {
        Student st = studentService.getStudentInfo(id);
        
        st.addPayments(paymentRecord);
        System.out.println("entered into do payment");
    

        
        
            studentService.addStudent(st);
      
        
        paymentService.doPayment(paymentRecord);
        return "redirect:{id}/payments";
    }

Please suggest. I am stuck here


Solution

  • You can do this different ways.

    But first, let's shorten the post method annotation from:

    @RequestMapping(method = RequestMethod.POST, value = "/{id}/payments")

    to

    @PostMapping("/{id}/payments")

    I would also change the variable id to studentId to make it more clear for the next person reading your code.

    Now, include the variable as a hidden input type within the form tags:

    <input type="hidden" name="studentId" th:value="${student.id}">

    Then you can either

    a) Add a String studentId property to your PaymentRecord class. Then in the post method, you can call paymentRecord.getStudentId();

    or

    b) Add a request parameter for the studentId to your method mapped with @PostMapping. So your method signature can have @RequestParam(String studentId). In this case, the value of the studentId will be fully exposed to the user.

    or

    c) Use @RequestBody and map the values to a bean. You can read up on this topic further and look at some background with this question.