java - Thymeleaf:将输入文本作为表单操作中的参数传递

标签 java rest thymeleaf

我对 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/

相关文章:

java - RMI理解问题

枚举构造函数中的 Java 字节类型

Angular 5 : How do I wait for my service to finish and then proceed to the next task?

java - 使用例如 @RolesAllowed 进行 JAX-RS 1 (Jersey) 授权

java - Thymeleaf 数组元素连接

java - 为什么在 Controller 中使用 @GetMapping 而不是 @DeleteMapping 进行删除工作?

spring - CSS + Thymeleaf - CSS 未反射(reflect)在页面上

JAVA - 如何忽略所有包含非字母字母的单词

java - 使用Spring 3.0的MultipartHttpServletRequest时的请求大小限制

android - 正确的 Android REST 客户端