发出发布请求后,Spring Boot和Thymeleaf将保留在同一页面上

时间:2018-09-24 12:33:56

标签: spring spring-boot html-table model thymeleaf

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

enter image description here

搜索后:

enter image description here

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

表格:

  <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";
}

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

1 个答案:

答案 0 :(得分:1)

我想您可能喜欢这个项目。它与您所需要的类似: 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);
}

P.S:不要用罗马尼亚语:D

编写代码