Search code examples
htmlspringspring-bootthymeleaf

spring thymeleaf - delete object from html table and pass id to controller


I pass a list with objects from my controller to my html and thymeleaf creates a for every object in the list.

I want to delete an entry via a button and pass the object id to my controller in order to delete it from the database.

However when I handle the post request in my controller the id attribute is emtpy.

HTML with Thymeleaf:

<tbody>
     <tr th:each="user : ${users}">
       <td th:text="${user.personId}"></td>
       <td th:text="${user.firstName}"></td>
       <td th:text="${user.lastName}"></td>
       <td>
           <form th:action="@{delete_user}" method="post" th:object="${user}">
              <input type="hidden" th:field="${user.personId}"/>
              <button type="submit" value="Submit" class="btn btn-danger">Delete</button>
           </form>
       </td>
     </tr>
</tbody>

Controller:

@RequestMapping(value = "/delete_user", method = RequestMethod.POST)
public String handleDeleteUser(@ModelAttribute("user") User user) {
    System.out.println(user.getPersonId());
    System.out.println("test");
    return "redirect:/external";
}

How can I make this work? Or is there another way?

Thanks!


Solution

  • you may try changing the th:action="@{delete_user}" to th:action="@{/delete_user}". or you can use path variable/ query string and pass the id using get method. e.g. html:

    <a th:href="|@{/delete_user/${user.personId}}|" class="btn btn-danger">Delete</a>
    

    controller:

    @RequestMapping(value = "/delete_user/{personId}", method = RequestMethod.GET)
    public String handleDeleteUser(@PathVariable String personId) {
        System.out.println(personId);
        System.out.println("test");
        return "redirect:/external";
    }
    

    or

    html:

    <a th:href="@{/delete_user(personId=${user.personId})}" class="btn btn-danger">Delete</a>
    

    controller:

    @RequestMapping(value = "/delete_user", method = RequestMethod.GET)
    public String handleDeleteUser(@RequestParam(name="personId")String personId) {
        System.out.println(personId);
        System.out.println("test");
        return "redirect:/external";
    }