我有一个简单的类注册地址
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ColorDto {
@Size(min = 2, max = 100, message = "The size must be in the range 2 to 100")
private String colorName;
}
在我的表单上,我添加了这个类的对象和数据库中已经存在的所有实体:
List<ColorDto> colors = colorService.getAll();
model.addAttribute("colors", colors);
model.addAttribute("colorForm", new ColorDto());
return "color";
表单本身是这样的:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Colors</title>
</head>
<body>
<h2>Colors</h2>
<div th:each="color : ${colors}">
<p>
Name : <span th:text="*{color.colorName}"></span>
</p>
</div>
<h4>Add new color</h4>
<div>
<form th:method="POST" th:action="@{/product/color}" th:object="${colorForm}">
<tr>
<td>Enter color:</td>
<td><input type="text" th:field="*{colorName}" required/></td>
<div th:if="${colorError}">
<div style="color: red" th:text="${colorError}"></div>
</div>
<div style="color:red" th:if="${#fields.hasErrors('colorName')}" th:errors="*{colorName}" >color error</div>
</tr>
<tr>
<td><input name="submit" type="submit" value="submit" /></td>
</tr>
</form>
</div>
<p><a href="/">Home</a></p>
</body>
</html>
我用以下方法处理这个表单中的数据:
@PostMapping("/color")
public String addNewColor(@ModelAttribute("colorForm") @Valid ColorDto colorDto,
HttpSession httpSession,
BindingResult bindingResult,
Model model){
if (bindingResult.hasErrors()) {
return "color";
}
如果正确填写字段,则该方法有效。如果我在那里发送了无效数据,程序就不会处理这些数据。也就是说,它根本不输入方法,并且发出Http Status 400。
您可以尝试更改addNewColor
函数中参数的顺序,以便bindingResult
紧随验证参数之后吗?
:
@PostMapping("/color")
public String addNewColor(HttpSession httpSession,
@ModelAttribute("colorForm") @Valid ColorDto colorDto,
BindingResult bindingResult,
Model model){
if (bindingResult.hasErrors()) {
return "color";
}