【发布时间】:2021-01-04 23:57:45
【问题描述】:
我已经搞砸了一个多小时,我知道我只是在看一些东西,所以有人可以向我指出吗?
我是 Spring 新手,我正在尝试使用 Thymeleaf 表单来处理我的 Spring 项目。
我的控制器:
public class ExampleController
{
@GetMapping("/sendForm")
public String sendForm(Model model)
{
User user = new User();
model.addAttribute("user", user);
return "addUser";
}
@PostMapping("/processForm")
public String processForm(User user) {
return "showMessage";
}
我的用户:
private String name;
private String occupation;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
还有我的 HTML:
<form action="#" th:action="@{/processForm}" th:object="${user}" method="post">
<input type="text" th:field="*{name}" />
<input type="submit" />
</form>
我的页面上显示的只是纯文本中的“addUser”。
编辑: https://github.com/agrapes22/employeeTrackerApp 已将完整代码添加到 GitHub。
提前致谢。
【问题讨论】:
-
您的
ExampleController是否用@Controller或@RestController注释? -
我认为是@RestController,但我两种方式都试过了
-
应该是
@Controller。只有在使用它时,Spring 才会将返回的 String 解释为视图。对于@RestController,返回字符串被视为响应正文。你在使用 Spring Boot 吗?在start.spring.io 上开始您的项目要容易得多(确保包含 Web 和 Thymeleaf 依赖项)。 -
我正在使用 Eclipse 插件进行 spring boot 和 maven。我的 pom.xml 文件中有 thymeleaf 和 web 依赖项。我用@Controller 试过了,但我仍然只有一个文本字符串
-
你能把你的代码放在 github 存储库上吗?您在此处发布的代码显然没有任何问题。