首页 > 解决方案 > 如何从 html 文件向控制器发送对象或数据?

问题描述

我在 html 文件中获得了“explorer”对象并可以对其进行分析:

<body>
<form th:action="@{/parsing}" method="post">
    <div class="w3-container">

        <table class="w3-table-all w3-card-4">
            <tr>
                <th>Id</th>
                <th>Query</th>
                <th></th>
            </tr>
            <tr>
                <td th:text="${explorer.getId()}"></td>
                <td th:text="${explorer.getQuery()}"></td>
                <td>
                    <input class="w3-button w3-blue w3-right" type="submit" value="Enter"/>
                </td>
            </tr>
        </table>

    </div>
</form>
</body>
</html>

现在我想用 post 方法发送它,但是当我提交时,我在“结果”中得到空值。

方法,从提交操作中获取查询:

@PostMapping("/parsing")
public ModelAndView parsing(
    @ModelAttribute Explorer explorer
    ){
    System.out.println("explorerId = " + explorer.getId());
    System.out.println("explorerId = " + explorer.getQuery());
    return new ModelAndView("result");
}

(它不会抛出任何异常,而是在控制台中只打印空数据)

在这种情况下如何发送任何对象以进行后期方法?

标签: javahtmlspringthymeleaf

解决方案


你很近。您的表单缺少命令对象属性。

我建议添加th:object="${explorer}"到您的表单标签中。

在您的GET方法中,仔细检查从控制器创建资源管理器对象的功能,然后在表单的请求属性中添加对象以命令对象,然后POST才能成功提交对象。

这个Thymeleaf 文档有比我在这个线程中组合的更多的答案。


推荐阅读