【问题标题】:Pass data from Thymeleaf to the controller using Spring使用 Spring 将数据从 Thymeleaf 传递到控制器
【发布时间】:2019-07-05 22:56:32
【问题描述】:

您好,我是 Spring 和 Thymeleaf 开发的新手,我正在尝试了解如何在 Thymeleaf 和控制器之间传递数据。我知道如何以相反的方式传递数据。使用从控制器传递到视图的数据,我正在构建一个表,其中有两列(一列是选择服务的按钮,另一列是服务名称)和与服务一样多的行我有。我想要做的是获取所选服务的ID(当按下添加按钮时,我只能按下一个按钮,但我可以按下所有其他按钮)并用它做一些后端处理(现在我只是想打印值)。另一件事是,一旦单击按钮,它会将我重定向到索引页面,但 /addService 在 URL 的末尾添加,我不希望这样(我想保持在具有相同 URL 的同一页面中)。 我怎么解决这个问题?

index.html

<table id="html-table" class="table table-hover table-clean table">
    <thead>
        <tr>
            <th>Select</th>
            <th>Service</th>
        </tr>
    </thead>
    <tbody>
        <tr th:each="serviceOffered : ${servicesOffered}">
            <td>
            <form action="#" th:value="${serviceOffered.id}" th:object="${serviceOffered}" th:action="@{/addService}" method="POST">
                <button type="submit" class="btn" name="${serviceOffered.id}">
                    <i class="fas fa-plus"></i>
                </button>
                </form>
            </td>
            <td th:value="${serviceOffered.name}" th:text="${serviceOffered.name}"></td>
        </tr>
    </tbody>
</table>

控制器

@RequestMapping(value="/addService", method = RequestMethod.POST)
public ModelAndView addService(@Valid ServiceOffered serviceOffered, BindingResult bindingResult){
    ModelAndView modelAndView = new ModelAndView();

    System.out.println("VALUE " + serviceOffered.getId());

    modelAndView.setViewName("/index");
    return modelAndView;
}

【问题讨论】:

    标签: java html spring thymeleaf


    【解决方案1】:

    您的表单有一个submit 类型的按钮。当您按下按钮时,它所做的就是提交表单。在您的控制器中,您重定向到 index 页面。如果您想单击按钮并仅发送服务的值而不重新加载页面,则需要使用 jquery 的ajax 调用。 docs这里是ajax调用的示例代码。

    $.ajax({
    url: '/your url',
    method: 'post',
    data: 'your data'
    }).then(function(response){
    // do what ever you want with your response.
    })
    

    记住:您需要在控制器类中的方法上添加@Responsebody 注解。

    【讨论】:

    • 实际上,我的最终目标是将所选值呈现到我选择值的表格旁边的表格中(只需将其视为具有所选服务列表的购物袋) .因此,我正在考虑使用控制器来获取选定的值,然后将其推回前面。所以可能我需要刷新页面,但老实说,我不知道如何编写整个内容(也许也可以使用一些 javascript 来完成)!
    • @andrea 您可以从控制器返回值。您将在response 中获得此值。然后,您可以更新 textdiv 或您正在使用的任何内容。就像$("#yourDivId").text(response)
    • 看看这个教程。这可能会有所帮助。 crunchify.com/…
    猜你喜欢
    • 2018-11-17
    • 2022-08-23
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 2017-04-18
    • 2019-04-14
    • 2017-05-21
    • 2018-01-18
    相关资源
    最近更新 更多