[英]@ModelAttribute is returning null values with thymeleaf
经过几天的研究,我很难为我的控制器方法找到解决方案。 我有两个似乎有问题的控制器方法。 保存方法是保存空值。 我不知道如何将输入到字段中的值绑定到列表/all。 一个用于使用输入字段创建值,另一个用于保存输入值并更新列表/全部。 我想获取我放入表单字段中的值,并有一个更新的列表/全部,其中包含新值。 请注意,我只是想保存整个类的十一个属性中的两个。 该类具有双精度值和 true/false。 除了重要的字符串值外,这些都被保存到数据库中。 提前感谢您的帮助!
第一种方法:
@GetMapping("/create")
public String showCreateForm(Model model, Branch branch) {
List<Branch> branches = new ArrayList<>();
BranchCreationDto branchesForm = new BranchCreationDto(branches);
for (int i = 1; i <= 1; i++) {
// the input field
branchesForm.addBranch(new Branch());
}
model.addAttribute("form", branchesForm);
return "branches/create";
}
此方法有一个输入字段,可以在其中设置 Branch 的值。
第二种方法:
@PostMapping("/saving")
public String saveBranches(@ModelAttribute BranchCreationDto form, Model model, Branch branch) {
// saves null but needs to be saving the values that are being typed into the field
this.branchRepository.saveAll(form.getBranches());
model.addAttribute("branches", branchRepository.findAll());
return "redirect:/all";
}
这种方法似乎有问题
this.branchRepository.saveAll(form.getBranches());
它正在返回空值。 我已经尝试将 branch.getName(), branch.getType() 放入参数中。 这是行不通的。
使用方法 /all 程序返回列表。
@GetMapping("/all")
public String showAll(Model model) {
model.addAttribute("branches", branchRepository.findAll());
return "branches/all";
}
这是我的包装类
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
public class BranchCreationDto {
@Autowired
private List<Branch> branches;
public BranchCreationDto(List<Branch> branches) {
this.branches = branches;
}
public BranchCreationDto() {
}
public void addBranch(Branch branch) {
this.branches.add(branch);
}
public List<Branch> getBranches() {
return branches;
}
public void setBranches(List<Branch> branches) {
this.branches = branches;
}
}
这是表格
<body>
<!-- Save -->
<form action="#" th:action="@{saving}" th:object="${form}"
method="post">
<fieldset>
<input type="submit" id="submitButton" th:value="Save"> <input
type="reset" id="resetButton" name="reset" th:value="Reset" />
<table>
<thead>
<tr>
<th>Branch</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr th:each="branch, itemStat : *{branches}">
<td><input th:field="*{branches[__${itemStat.index}__].branch}" /></td>
<td><input th:field="*{branches[__${itemStat.index}__].type}" /></td>
</tr>
</tbody>
</table>
</fieldset>
</form>
你做错了,价值不会通过这种方式从控制器传递到百里香叶。我会给你一个例子。 例子:
Controller:
Model and View model =new Model and View();
model .put ("branches", branch Repository.find All());
return model;
Thyme leaf:
<input id="branches" type="hidden" t h:value="${branches}" />
现在你的价值被传递给 id 分支。
只需将字段添加为隐藏输入,thymeleaf 就会发送您的更改:
<input type="hidden" th:field="*{branches}"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.