gpt4 book ai didi

java - 无法将基于 Thymeleaf 的 UI 表单中的值绑定(bind)到 Spring Boot 中的 Controller

转载 作者:行者123 更新时间:2023-11-30 02:12:58 25 4
gpt4 key购买 nike

我的应用程序无法将基于 Thymeleaf + HTML 的 UI 中的表单值绑定(bind)到 Spring Boot Controller 。

当我在 Controller 中执行 System.out.println 时,我得到的值为 null

index.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<p>Get your greeting <a href="/greeting">here</a></p>
<form action="/publishMessage" method="post">
<table>
<tr>
<th>CHARGE</th>
</tr>
<tr>
<td>
<textarea th:field="*{messageBody}" name="" cols="90" rows="40">
{
"firstname": "Jose",
"lastname": "Long"
}
</textarea>
</td>
</tr>
<tr>
<td><input type="submit" name="btnSubmit" value="Publish CHARGE message"></td>
</tr>
</table>
</form>
</body>
</html>

PublishMessageController.java

@Controller
public class PublishMessageController {
@PostMapping("/publishMessage")
public String publishMessage(Message message, BindingResult bindingResult, Model model) {
System.out.println("into the publishMessage method..........");
String messageBody = message.getMessageBody();
System.out.println("messageBody: " + messageBody);
return "result";
}
}

Message.java

import lombok.*;

@Data
@Getter
@Setter
@NoArgsConstructor
public class Message {
private String messageBody;
}

输出:

into the publishMessage method..........
messageBody: null

最佳答案

您的消息永远不会放入模型中,因此您不能将其用作 Controller 中的变量。

Spring model attributes

Handling the command object

顺便说一句:该方法不应返回“结果”,而应返回消息正文的字符串。

将您的 messageBody 放入显示表单的模型中:

@RequestMapping(value = "/showForm", method=RequestMethod.GET)
public String showForm(Model model) {
...
String messageBody = ...
model.addAttribute("messageBody", messageBody);
...
}

要在您的 View 中使用此功能,请将 th:actionth:object 添加到您的表单中:

<form action="#" th:action="@{/publishMessage}" th:object="${messageBody}" method="post">
...
</form>

现在您可以通过参数中的注释在 Controller 方法中使用它:

@PostMapping("/publishMessage")
public String publishMessage(@ModelAttribute(value="messageBody") String messageBody, BindingResult bindingResult, Model model) {
...
return messageBody;
}

当然,您可以使用整个消息而不是正文来执行此操作。

关于java - 无法将基于 Thymeleaf 的 UI 表单中的值绑定(bind)到 Spring Boot 中的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49559974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com