我正在尝试使用spring-boot-starter-web和thymeleaf创建一个Web应用程序。作为一个起点,我使用Spring的验证表单输入 - 入门指南(https://spring.io/guides/gs/validating-form-input/)因为“这些指南旨在尽快提高您的工作效率 - 使用最新的Spring项目版本和技术春天团队。“
我已将年龄输入字段更改为从服务填充的年龄下拉列表。我修改后的代码如下:
package hello;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Controller
public class WebController implements WebMvcConfigurer {
@Autowired
AgeService ageService;
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/results").setViewName("results");
}
@GetMapping("/")
public String showForm(Model model) {
PersonForm personForm = new PersonForm();
model.addAttribute("personForm", personForm);
List<Integer> validAges = ageService.getValidAges();
model.addAttribute("validAges", validAges);
return "form";
}
@PostMapping("/")
public String checkPersonInfo(@Valid PersonForm personForm, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "form";
}
return "redirect:/results";
}
}
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<form action="#" th:action="@{/}" th:object="${personForm}" method="post">
<table>
<tr>
<td>Name:</td>
<td><input type="text" th:field="*{name}"/></td>
<td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</td>
</tr>
<tr>
<td>Age:</td>
<td><select th:field="*{age}">
<option value="">Please select ...</option>
<option th:each="validAge:${validAges}" th:value="${validAge}" th:text="${validAge}"></option>
</select></td>
<td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">Age Error</td>
</tr>
<tr>
<td>
<button type="submit">Submit</button>
</td>
</tr>
</table>
</form>
</body>
</html>
首次显示表单时,一切正常,但如果出现验证错误且表单重新显示,则下拉列表中只显示“请选择..”选项。
使这项工作的推荐技术是什么?
答案 0 :(得分:1)
没有填充下拉列表,因为在bindingResult对象发现错误之后,在返回表单之前,似乎没有将validAges列表作为属性添加到模型中。
请添加:
模型模型,作为checkPersonInfo的参数,如图所示
CheckPersonInfo(Model model, ...)
在bindingResult.hasErrors块中将validaAges添加到模型中,如图所示
if(bindingResult.hasErrors()){
model.addAttribute("validAges", ageService.getValidAges());
return "form";
}