0
所以我下面寫在Thymeleaf:Thymeleaf形式不發送實際的對象ID爲Java控制器
<form th:action="@{|/recipes/${recipe.id}/delete|}" method="post" id="recipeDeleteForm">
</form>
而且在Java中的以下內容:
@RequestMapping(value = "/recipes/{recipeId}/delete", method = RequestMethod.POST)
public String deleteRecipe(@PathVariable Long recipeId, RedirectAttributes redirectAttributes){
Recipe recipe = recipeService.findOne(recipeId);
recipeService.delete(recipe);
return "redirect:/";
}
的問題是,當我按下瀏覽器上的刪除按鈕時,請求只會將數字1發送給控制器,而不是發送特定的對象ID。所以它會一直刪除列表中的第一個元素,而不是我選擇的元素。
編輯:其實,這是增量式的。如果我第一次從列表中刪除一個隨機對象,它將從列表中刪除第一個項目,如果從列表中刪除另一個隨機元素,它將刪除第二個,等等...
Something否則添加將是,如果我嘗試去詳細頁面,或者我嘗試編輯對象,這不會發生。它會將正確的ID發送給控制器。這隻發生在刪除請求上。
這裏的一個重要區別是編輯和細節操作是鏈接,而刪除是表單操作。
這是整個標記文件的樣子:
<!DOCTYPE html>
<html lang="en">
<head th:replace="layout :: head"></head>
<body>
<nav th:replace="layout :: nav"></nav>
<div class="grid-container">
<div th:replace="layout :: logo"></div>
<div class="grid-100">
<div class="recipes">
<div class="grid-100 row controls">
<div class="grid-30">
<select>
<option value="">All Categories</option>
<option value="breakfast">Breakfast</option>
<option value="lunch">Lunch</option>
<option value="dinner">Dinner</option>
<option value="dessert">Dessert</option>
</select>
</div>
<div class="grid-40">
<input placeholder="Search"></input>
</div>
<div class="grid-30">
<div class="flush-right">
<a th:href="@{/recipes/add-new-recipe}"><button>+ Add Recipe</button></a>
</div>
</div>
</div> <div class="clear"></div>
<div class="grid-100 row addHover" th:each="recipe : ${recipes}">
<a th:href="@{|/recipes/${recipe.id}/detail|}">
<div class="grid-70">
<p>
<span><img th:src="@{/images/favorite.svg}" height="12px"/> </span>
<span th:text="${recipe.name}"></span>
</p>
</div>
</a>
<div class="hoverBlock">
<div class="grid-30">
<div class="flush-right">
<p>
<a th:href="@{|/recipes/${recipe.id}/edit|}"> <img th:src="@{/images/edit.svg}" height="12px"/> Edit </a>
<a href="javascript:;" onclick="document.getElementById('recipeDeleteForm').submit();"> <img th:src="@{/images/delete.svg}" height="12px"/> Delete </a>
<form th:action="@{|/recipes/${recipe.id}/delete|}" method="post" id="recipeDeleteForm">
</form>
</p>
</div>
</div>
</div>
</div><div class="clear"></div>
<div class="row"> </div>
</div>
</div>
</div>
</body>
</html>
@ {|/recipes /是一個收藏n/array/list,所以你需要迭代它 – reos