所以我在Thymeleaf写了以下内容:
<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。所以它总是会删除列表中的第一个元素,而不是我选择的元素。
编辑:实际上,这是递增的。如果我第一次从列表中删除一个随机对象,它将从列表中删除第一个项目,如果我从列表中删除另一个随机元素,它将删除第二个,依此类推......要添加的其他内容是,如果我尝试转到详细信息页面,或者尝试编辑该对象,则不会发生这种情况。它会将正确的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>
答案 0 :(得分:0)
问题是我使用<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>
解决方案是在表单标签内使用按钮,并消除锚点:
<form th:action="@{|/recipes/${recipe.id}/delete|}" method="post" id="recipeDeleteForm">
<button type="submit">Delete</button>
</form>