【问题标题】:Pass data from Thymeleaf template to springboot controller将数据从 Thymeleaf 模板传递到 springboot 控制器
【发布时间】:2021-04-20 15:10:36
【问题描述】:

我有一个使用 Springboot 和 Thymeleaf 模板编写的简单 Web 应用程序。报表控制器从表单接收数据并构建作为模型属性添加的 TestPlanReportResponse 对象,如下所示:

@PostMapping("/report")
public String homeSubmit(@ModelAttribute HomeFormInput homeFormInput, Model model, Errors errors) {
    final TestPlanReportResponse response = new TestPlanReportResponse(homeFormInput);
    model.addAttribute("allData", response);
    return "charts";
}

我可以在“图表”百里香模板中使用该数据并显示我需要的数据,但我需要在单击按钮时将完全相同的对象发送回控制器,但我得到了 TestPlanReportResponse 对象作为参数并设置了空值。

@PostMapping("/report/send")
public String sendReport(@ModelAttribute TestPlanReportResponse reportData, Model model) {
    //reportData contains just nulls
}

这是我的按钮在图表模板中的设置方式:

<form action="#" th:action="@{/report/send}" th:object="${allData}" method="post">
        <button type="submit">Send the report</button>
</form>

所以我的问题是如何将对象从百里香模板发送回来?我是否应该创建一个隐藏的输入并将“allData”对象放在那里只是为了将其发回?在我看来,它就像肮脏的黑客。将数据传回的适当方法是什么?我想让这个应用程序无状态,所以不要将数据存储在服务器端。

【问题讨论】:

    标签: spring-boot thymeleaf


    【解决方案1】:

    当我使用 Spring、Thymeleaf 和表单时,我们遇到了同样的问题,在表单、模板和不同控制器之间来回传递数据。 你的建议就是我们所做的,我们使用了尽可能脏的隐藏输入,这是标准的建议答案,我们没有找到更好的答案。

    您需要创建一个输入,一个类型一个值并将其链接到一个字段,如下所示:

        <form action="#" th:action="@{/report/send}" th:object="${allData}" method="post">
       <input type="hidden" th:value="*{allDataValue1}" th:field="*{allDataField1}" />
    //Do this for all your attributes/values that you wish to pass to the controller
                <button class="btn btn-info btn-lg btn-block" type="submit">Send the report</button>
        </form>
    

    虽然,我找到了这个answer,你可以试试看这个帖子

    【讨论】:

    • 谢谢@Youri,看来这是解决问题的方法
    • 很高兴听到它
    猜你喜欢
    • 2018-06-28
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 2019-04-01
    • 2022-08-23
    • 2014-12-14
    • 2018-11-17
    • 2021-09-30
    相关资源
    最近更新 更多