使用Spring和Html从存储库中删除元素

时间:2017-09-13 13:49:02

标签: html spring thymeleaf

我正在尝试从CrudRepository中删除一个主题,但我尝试创建的复选框不会显示出来。 我有一个可以正常使用的添加方法,但删除不会。

HTML: hello.html 用于导航和头部碎片

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org/"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head th:fragment="head">
    <title> Lunch Planner Beta </title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css"/>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script>

</head>
<body>
<h1 th:inline="text">Hello  [[${#httpServletRequest.remoteUser}]]!</h1>

<nav th:fragment="navigation">
    <a href="/api/topics">List</a> |
    <a href="/addTopic">Add</a> |
    <a th:href="/removeTopic">Remove</a>
</nav>


<form th:action="@{/home}" method="get">
    <input type="submit" value="Home"/>
</form>

<br/>

<form th:action="@{/logout}" method="post">
    <input type="submit" value="Sign OUT"/>
</form>
</body>
</html>

TopicController.java

的部分
@RequestMapping(method = RequestMethod.POST, value = "/remove", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
@Transactional
public ModelAndView deleteTopic(Long id, HttpServletResponse response, Errors errors){
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    model.addObject("topic",topicService.getTopic(id));
    topicService.deleteTopic(id);

    return new ModelAndView("home");
}

HTML: removeTopic.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head th:replace="hello :: head">
</head>

<body class="container">

<nav th:replace="hello :: navigation"></nav>

<form th:action="@{/api/remove}" th:object="${topic}" method="post">
    <div th:each="topic: ${topic}" class="checkbox">
        <input type="radio" name="id" th:value="${topics.id}" th:id="${topics.id}"/>
        <label th:for="${topics.id}" th:text="${topics.category}"></label>
        <br/>
    </div>

    <input type="submit" value="Remove Topic"/>
</form>

</body>
</html>

以下是发生的事情:

enter image description here

2 个答案:

答案 0 :(得分:1)

你的问题在循环中,你使用相同的对象来迭代自己

th:each="topic: ${topic}"

你应该有类似的东西

<div th:each="item: ${topics}" class="checkbox">
    <input type="radio" name="id" th:value="${item.id}" th:id="${item.id}"/>
    <label th:for="${item.id}" th:text="${item.category}"></label>
    <br/> <!-- Do not use this tag to add vertical space, use css classes-->
</div>

答案 1 :(得分:0)

感谢https://stackoverflow.com/users/2757561/cralfaro我们能够修复控制器和removeTopic.html之间的连接

问题是

上的 hello.html
<a th:href="/removeTopic">Remove</a>

这个应该如何:

<a th:href="@{/api/removeTopic}">Remove</a>