首页 > 解决方案 > Spring Boot 和 Thymeleaf 在发布请求时保持在同一页面上

问题描述

我创建了一个网络应用程序,用于搜索在线汽车广告并在发布请求后用几个表格填充页面。它看起来像这样:

在此处输入图像描述

搜索后:

在此处输入图像描述

每个表格元素都有一个保存按钮,应该将这些值保存到数据库中,但我的问题是提交发布请求后页面会刷新。如何在不刷新页面的情况下执行此操作?

桌子:

  <form th:action="@{/saveAd}" method="POST">
    <table class="table table-sm table-hover">
      <thead class="thead-dark">
        <tr>
            <th>Imagine</th>
            <th>Titlu Anunt</th>
            <!-- <th style="width: 16.66%">Link</th> -->
            <th>Pret</th>
            <th>Oras</th>
       </tr>
     </thead>
     <tbody id="myTable">
       <th:block th:each="element : ${lista}">
        <trth:onclick="'javascript:rowClicked(\'' + ${element.url} + '\');'">
          <td><img th:src="@{${element.img}}" class="size" /></td>
          <td th:text="${element.title}"></td>
          <td th:text="${element.pret}"></td>
          <td th:text="${element.oras}"></td>
          <td><input class="btn btn-danger" type="submit"value="Save"></td>
          </tr>
      </th:block>
    </tbody>

控制器:

@RequestMapping(path = "/saveAd", method = RequestMethod.POST)
public String saveAd(@ModelAttribute("adValue") AdValue adValue) {
    System.out.println(adValue.getImg());
    System.out.println(adValue.getLink());
    System.out.println(adValue.getOras());
    System.out.println(adValue.getPret());
    System.out.println(adValue.getTitle());
    return "home";
}

而且,按下保存按钮后如何将列表绑定到模型对象?

标签: springspring-boothtml-tablemodelthymeleaf

解决方案


我想你可能会喜欢这个项目。它与您需要的相似: https ://github.com/adinafometescu/tutorials/tree/master/spring-elasticsearch

您可以使用 .bootstrapTable()。这是一种动态更新表格的方法。

<table id="car-table" class="table table-striped">
    <thead>
    <tr>
        <th data-field="id">Id</th>
        <th data-field="title">Title</th>
        <th data-field="price">Price</th>
        <th data-field="city">City</th>
        <th data-width="10" data-formatter="saveButtonFormatter"/>
    </tr>
    </thead>
</table>

美妙之处在于它将数据字段映射到java对象。js东西:

function saveButtonFormatter(value, row, index){
    var adId = row.id;
    return "<button class=\"btn btn-danger \" data-title=\"Save\" 
    data-toggle=\"modal\" onclick=\"saveAd(\'"+adId+"\')\" 
    </button>"
}

函数 saveAd(adId) 将调用其余端点并在成功时更新引导表。

我看到在你的百里香叶中你没有输入。如果您不需要用户输入,我建议不要发布您的整个对象,只需要 id。

// anotate the controller class with @RestController

@Autowired
AdService adService;

@PostMapping(path = "/ad/{id}")
public ResponseEntity<?> saveAd(@PathVariable("id") String id) {
    adService.saveAd(id);
    return new ResponseEntity<>(HttpStatus.ACCEPTED);
}

PS:不要用罗马尼亚语写代码:D


推荐阅读