hibernate validtor不工作,bindingresult.haserrors在spring boot中始终返回false

q5iwbnjs  于 2021-08-20  发布在  Java
关注(0)|答案(0)|浏览(350)

我试图简化验证,但问题是没有应用约束。这是我的模型级客户。

  1. package mvc;
  2. import jakarta.validation.constraints.NotNull;
  3. import jakarta.validation.constraints.Size;
  4. public class Customer {
  5. private String firstName;
  6. @NotNull(message="is required")
  7. @Size(min=1, message="is required")
  8. private String lastName;
  9. public String getFirstName() {
  10. return firstName;
  11. }
  12. public void setFirstName(String firstName) {
  13. this.firstName = firstName;
  14. }
  15. public String getLastName() {
  16. return lastName;
  17. }
  18. public void setLastName(String lastName) {
  19. this.lastName = lastName;
  20. }
  21. }

这是我的控制器。问题是bindingResult.haserrors()总是返回false

  1. package mvc;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.ui.Model;
  4. import org.springframework.validation.BindingResult;
  5. import org.springframework.web.bind.annotation.ModelAttribute;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import jakarta.validation.Valid;
  8. @Controller
  9. @RequestMapping("/customer")
  10. public class CustomerController {
  11. @RequestMapping("/showForm")
  12. public String showForm(Model theModel) {
  13. theModel.addAttribute("customer", new Customer());
  14. return "customer-form";
  15. }
  16. @RequestMapping("/processForm")
  17. public String processForm(
  18. @Valid @ModelAttribute("customer") Customer theCustomer,
  19. BindingResult theBindingResult) {
  20. System.out.println("Last name: |" + theCustomer.getLastName() + "|");
  21. if (theBindingResult.hasErrors()) {
  22. return "customer-form";
  23. }
  24. else {
  25. return "customer-confirmation";
  26. }
  27. }
  28. }

这是我的customer-form.jsp

  1. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
  2. <html>
  3. <head>
  4. <title>Customer Registiration form</title>
  5. <style type="text/css">
  6. .error{color: red}
  7. </style>
  8. </head>
  9. <body>
  10. <form:form action="processForm" modelAttribute="customer">
  11. FirstName: <form:input path="firstName"/>
  12. <br><br>
  13. LastName (*): <form:input path="lastName"/>
  14. <form:errors path="lastName" cssClass="error"/>
  15. <input type="submit" value="Submit" />
  16. </form:form>
  17. </body>
  18. </html>

这是我的customer-confirmation.jsp

  1. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>Customer confirmation</title>
  6. </head>
  7. <body>
  8. The customer is confirmed: ${customer.firstName} ${customer.lastName}
  9. </body>
  10. </html>

注意:我添加了HibernateValidator7JAR。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题