2017-04-25 65 views
0

我将一个列表与来自我的控制器的对象一起传递给我的html,并且thymeleaf为列表中的每个对象都创建一个列表。spring thymeleaf - 从html表中删除对象并将id传递给控制器​​

我想通过按钮删除一个条目,并将对象ID传递给我的控制器,以便从数据库中删除它。

但是,当我在我的控制器中处理post请求时,id属性是emtpy。

HTML与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> 

控制器:

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

我怎样才能使这项工作? 还是有另一种方式?

谢谢!

回答

2

您可以尝试将th:action="@{delete_user}"更改为th:action="@{/delete_user}"。 或者您可以使用路径变量/查询字符串并使用get方法传递该ID。 例如 HTML:

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

控制器:

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

HTML:

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

控制器:

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

用method = GET删除一个用户,这是一个很好的做法吗? – user641887

+0

@ user641887其实,在这里你不是通过GET方法删除用户的,你只是使用GET方法传递一个id,删除操作可能会使用一些POST方法web服务来执行。 –

相关问题