我对 Thymeleaf 还很陌生,所以我正在努力解决这个问题。
我想在提交表单时将参数传递给 Controller ,其中包含文本字段的值。
这是我的 Controller :
@PostMapping("/postEndpoint/{myid}")
public String pidUserSubmit(@PathVariable(value = "myid") String myid) {
log.debug("*** MY ID: {}", myid);
return "redirect:/someOtherPage";
}
这就是我定义文本输入的方式:
<input id="myid" name="myid" type="text" maxlength="26" title="Please enter a valid ID" class="texter" th:value="*{myid}">
这是我在 thymeleaf 的 html 文件中尝试过的:
<form name="myform" id="myform" action="#" th:action="@{/postEndpoint/__${myid}__}" method="post">
我收到此日志: *** 我的 ID:空
<form name="myform" id="myform" action="#" th:action="@{/postEndpoint/${myid}}" method="post">
我收到此日志: *** 我的 ID:${myid}
<form name="myform" id="myform" action="#" th:action="@{/postEndpoint/{myid}(myid=${myid})}" method="post">
这甚至没有到达 Controller
如有任何帮助,我们将不胜感激! :)
最佳答案
这不是这样工作的。与所有服务器端技术一样,Thymeleaf 模板在发送给用户之前执行,因此它无法知道用户将输入什么并将其插入到 action
属性中。
您可以使用 JavaScript 执行类似的操作,但使用常规 HTML 表单会容易得多。这要求您不要使用路径变量,而是在 Controller 中使用请求参数:
@PostMapping("/postEndpoint")
public String pidUserSubmit(@RequestParam(name = "myid") String myid) {
log.debug("*** MY ID: {}", myid);
return "redirect:/someOtherPage";
}
<小时/>
<form th:action="@{/postEndpoint}" th:object="${mymodelobject}">
<input name="myid" type="text" th:value="*{myid}">
</form>
(如果您想使用 *{...,请不要忘记将
语法。)th:object
与具有属性 myid
的对象一起使用。 }
关于java - Thymeleaf:将输入文本作为表单操作中的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45716052/