如何正确验证你的类

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

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

  1. @Data
  2. @Builder
  3. @NoArgsConstructor
  4. @AllArgsConstructor
  5. public class ColorDto {
  6. @Size(min = 2, max = 100, message = "The size must be in the range 2 to 100")
  7. private String colorName;
  8. }

在我的窗体上,我添加了这个类的一个对象和数据库中已经存在的所有实体:

  1. List<ColorDto> colors = colorService.getAll();
  2. model.addAttribute("colors", colors);
  3. model.addAttribute("colorForm", new ColorDto());
  4. return "color";

表单本身如下所示:

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Colors</title>
  6. </head>
  7. <body>
  8. <h2>Colors</h2>
  9. <div th:each="color : ${colors}">
  10. <p>
  11. Name : <span th:text="*{color.colorName}"></span>
  12. </p>
  13. </div>
  14. <h4>Add new color</h4>
  15. <div>
  16. <form th:method="POST" th:action="@{/product/color}" th:object="${colorForm}">
  17. <tr>
  18. <td>Enter color:</td>
  19. <td><input type="text" th:field="*{colorName}" required/></td>
  20. <div th:if="${colorError}">
  21. <div style="color: red" th:text="${colorError}"></div>
  22. </div>
  23. <div style="color:red" th:if="${#fields.hasErrors('colorName')}" th:errors="*{colorName}" >color error</div>
  24. </tr>
  25. <tr>
  26. <td><input name="submit" type="submit" value="submit" /></td>
  27. </tr>
  28. </form>
  29. </div>
  30. <p><a href="/">Home</a></p>
  31. </body>
  32. </html>

我用以下方法处理此表格中的数据:

  1. @PostMapping("/color")
  2. public String addNewColor(@ModelAttribute("colorForm") @Valid ColorDto colorDto,
  3. HttpSession httpSession,
  4. BindingResult bindingResult,
  5. Model model){
  6. if (bindingResult.hasErrors()) {
  7. return "color";
  8. }

如果我正确地填写了字段,这个方法就行了。如果我在那里发送无效数据,程序将不处理这些数据。也就是说,它根本不进入该方法,并且发出http状态400。

4dc9hkyq

4dc9hkyq1#

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

  1. @PostMapping("/color")
  2. public String addNewColor(HttpSession httpSession,
  3. @ModelAttribute("colorForm") @Valid ColorDto colorDto,
  4. BindingResult bindingResult,
  5. Model model){
  6. if (bindingResult.hasErrors()) {
  7. return "color";
  8. }

相关问题