【问题标题】:How to retrieve data from a th:value (thymeleaf) in the controller?如何从控制器中的 th:value (thymeleaf) 中检索数据?
【发布时间】:2021-03-03 00:20:42
【问题描述】:

我需要在 Spring MVC 控制器中检索来自视图中 th:value 字段的内容。 使用 RequestParam 尝试了下面的代码,但没有成功。

表格代码:

<form action="form1" method="post">
<input type="text" th:value="${personId}"/>
<input type="submit" name="btnSubmit" value="Submit">
</form>

Spring MVC 控制器

@RequestMapping(value="/form1", params = "btnSubmit", method = RequestMethod.POST)
public String formMethod (@RequestParam("personId") int personId) {
    return "";
}

注意:我知道这也可以通过 th:field 替换 th:value、在表单标签中添加 th:object 并在控制器中使用 @ModelAttribute 来实现。但这需要创建一个完整的对象并将表单与对象紧密结合。不想那样做。想要一些更简单的东西,只需要一个字段,让表单绑定到另一个对象。因此,想知道当它是一个 th:value 时是否可以检索该数据(或其他适用于单个字段的数据)。

【问题讨论】:

  • 您的输入字段是 id 且无名的,您必须将其命名为“personId”,因此请求中会出现“personId”
  • 或许你可以试试th:name="personId"?
  • 就是这样,伙计们。我添加了名称,它起作用了!纯 html 名称或 th:name。我没有那个,因为在我使用 th:field 的示例中,名称不需要工作。出于某种原因 th:value 需要它。谢谢。
  • 你可以试试&lt;input type="text" name="personId"/&gt;。删除th:value。

标签: java spring spring-mvc thymeleaf


【解决方案1】:

您无需使用th:value 将数据返回给控制器。你需要在你的标签form中配置th:object:

<form action="form1" method="post" th:object="${person}">

然后你把th:value改成name = "personId":

<input type="text" name="personId" />

在控制器中需要更改参数方法:

@RequestMapping(value="/form1", params = "btnSubmit", method = RequestMethod.POST)
public String formMethod (@Valid Person person, Model Model) {
    return "";
}

Obs.:如果你的 html 页面中有更多的提交按钮,你可以使用params = "btnSubmit=Submit"。

了解详情: https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    相关资源
    最近更新 更多