【发布时间】:2019-05-22 02:01:09
【问题描述】:
经过几天的研究,我无法为我的控制器方法找到解决方案。我有两种似乎有问题的控制器方法。节省方法是保存空值。我不知道如何将输入到字段中的值绑定到列表/all。一个用于使用输入字段创建值,另一个用于保存输入值并更新列表/全部。我想获取我放入表单字段的值,并使用新值更新列表 /all。请注意,我只是试图保存整个类的 11 个属性中的两个。该类具有双值和真/假。这些都被保存到数据库中,除了重要的字符串值。提前感谢您的帮助!
第一种方法:
@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>
【问题讨论】:
标签: java spring-mvc spring-boot controller thymeleaf