我是 Thymeleaf 的新手,我尝试使用 Thymeleaf 和 Spring MVC 执行一个简单的表单提交示例。我根据 Thymeleaf 文档编写了代码。但是我在 Controller 中得到空值。
<form action="thymeleafexample/thymeleaf.html" th:action="@{/thymeleaf}"
th:object="${loginModel}" method="post">
<table>
<tr>
<td th:text="#{emp.empId.label}">Emp ID</td>
<td><input type="text" th:field="*{empId}"/></td>
</tr>
<tr>
<td th:text="#{emp.empName.label}">Emp Name</td>
<td><input type="text" th:field="*{empName}"/></td>
</tr>
<tr>
<td>
<button type="submit" name="save" th:text="#{${'.emp.button.label'}}">submit</button>
</td>
</tr>
</table>
</form>
我的 Controller 是
@RequestMapping(value = "/thymeleaf", params = {"save"})
public String save(@Validated LoginModel loginModel, final BindingResult bindingResult, ModelMap model) {
if (bindingResult.hasErrors()) {
return "thymeleaf";
}
System.out.println(loginModel);
System.out.println(loginModel.getEmpName());
return "/thymeleaf";
}
我的模型类是
public class LoginModel {
private String empName;
private int empId;
public void setEmpId(int empId) {
this.empId = empId;
}
public int getEmpId() {
return empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
}
最佳答案
我遇到了同样的问题 as OP mentioned ,为具有必要成员字段的 POJO(Model) 类创建构造函数并使用 th:field=*{foo}
而不是 th:value=${foo}
解决了我的问题。
关于java - 无法在 spring mvc 中获取 thymeleaf 表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24671221/