2017-04-25 10 views
0

私のコントローラからmyHtmlにオブジェクトのリストを渡し、thymeleafはリスト内のすべてのオブジェクトに対してaを作成します。spring thymeleaf - htmlテーブルからオブジェクトを削除し、コントローラにIDを渡す

ボタンからエントリを削除し、オブジェクトIDをコントローラに渡してデータベースから削除したいとします。

私のコントローラで投稿要求を処理するとき、id属性はemtpyです。 Thymeleafと

HTML:

<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

メソッドをGETしてユーザーを削除するとよいでしょうか? – user641887

+0

@ user641887実際、GETメソッドを使用してユーザーを削除しているわけではなく、GETメソッドを使用してIDを渡しているだけで、POSTメソッドの一部のWebサービスを使用して削除操作を実行できます。 –

関連する問題