如何正确验证你的类

iibxawm4  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(213)

我有一个注册地址的简单类

@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状态400。

4dc9hkyq

4dc9hkyq1#

你能试着改变参数的顺序吗 addNewColor 因此 bindingResult 是否紧跟在已验证的参数之后?
这样地:

@PostMapping("/color")
    public String addNewColor(HttpSession httpSession,
                              @ModelAttribute("colorForm") @Valid ColorDto colorDto,
                              BindingResult bindingResult,
                              Model model){
        if (bindingResult.hasErrors()) {
            return "color";
        }

相关问题