spring thymeleaf - 从html表中删除对象并将id传递给controller

时间:2017-04-25 09:00:41

标签: html spring spring-boot thymeleaf

我将一个包含来自我的控制器的对象的列表传递给我的html,百里香为列表中的每个对象创建一个。

我想通过按钮删除条目并将对象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";
}

我该如何使这项工作? 或者还有另一种方式吗?

谢谢!

3 个答案:

答案 0 :(得分: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";
}

答案 1 :(得分:1)

下面是视图部分。

<tbody>
<tr th:each="income : ${incomes}">
<td th:text="${income.createDate}"></td>
<td th:text="${income.name}"></td>
<td th:text="${income.description}"></td>
<td th:text="${income.amount}"></td>
<td><a th:href="@{/income/edit/{id}(id=${income.id})}" class="btn btn-primary"><i class="fas fa-user-edit ml-2"></i></a></td>
<td><a th:href="@{/income/delete/{id}(id=${income.id})}" class="btn btn-primary"><i class="fas fa-user-times ml-2"></i></a></td>
</tr>
</tbody>

下面是控制器

@GetMapping("/delete/{id}")
public String deleteIncome(@PathVariable(value = "id") Long id,Model model) {
    Income note = incomeRepo.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException("Income", "id", id));
    incomeRepo.delete(note);
    model.addAttribute("incomes",incomeRepo.findAll());
    return "viewIncome";
}

在上述来自视图部分的代码中,我将id传递给了控制器。然后在控制器中通过找到ID删除相关记录。

答案 2 :(得分:0)

带有Thymeleaf的HTML:

EXEC SQL
SELECT nvl(COLUMN.NAME,null) into :h_HOST_VARIABLE :i_HOST_VARIABLE
FROM TABLE_NAME
WHERE
someCondition......

控制器:

import os, datetime
import requests
from rfeed import Item, Feed
from flask import Flask, jsonify, request

app = Flask(__name__)
app.config["DEBUG"] = True

@app.route("/rss/summary", methods=['GET'])
def summary():
    response = requests.get("https://www.technologyreview.com/c/computing/rss/")
    if response.status_code is 200:
        data = response.json()
        article_sum = []
        for articles in data:
            article_sum.append(
                Item(
                    title = articles['title'],
                    author = articles['author'],
                    pubDate = datetime.datetime(2014, 12, 29, 10, 00),
                    link = articles['url']
                )
            )
        feed = Feed(
            title = "A summary feed listing",
            link = "http://127.0.0.1:5000/rss/summary",
            description = "a summary feed listing the title, author, date, and link for 10 most recent articles",
            language = "en-US",
            lastBuildDate = datetime.datetime.now(),
            items = article_sum
        )
        return feed.rss()
    else:
        return response.status_code
if __name__ == '__main__':
    app.run()

OR

带有Thymeleaf的HTML:

  <table class="table table-responsive">

        <th >
            <td>ID</td>
            <td>Name</td>
            <td>Address</td>
            <td>Delete</td>
        </th>

        <tr th:each="student : ${students}">
            <td th:text="${student.id}"/>
            <td th:text="${student.name}"/>
            <td th:text="${student.address}"/>
            <td >
              <form th:action="@{delete}" method="post">
                  <input type="hidden" name="id" th:value="${student.id}" />
                  <input type="submit" value="Delete" class="btn btn-danger" />
              </form>
            </td>
        </tr>
    </table>

控制器:

@RequestMapping(value = "/delete", method = RequestMethod.POST)
private String deleteStudent(@RequestParam String id){
    System.out.println("Student_Id : "+id);
    return "redirect:/display";
}