Spring MVC 验证状态 400

Spring MVC validation status 400

我刚开始学习 Spring 并坚持使用表单验证(有 dao/service 和所有默认设置)

我尝试做一个验证任务来防止在字段中插入超过 3 个符号

@Size (min = 1, max = 3)

之后我想将表单数据插入DB并输出到我的主页上,当数据满足我的验证并且由1到3个符号组成时,一切都可以,但是当这些条件不满足时并且我尝试插入 4 个或更多符号,我收到 HTTP STATUS 400。没有数据库插入,也没有视图输出。所以我知道有验证,但是我不明白为什么它会显示 HTTP STATUS 400

@Controller
public class BookController {

    @Autowired
    private BookService bookService;

    @RequestMapping(value = "addBook", method = RequestMethod.GET)
    public String addUser(Model model) {

        model.addAttribute("user", new ValidationField());
        model.addAttribute("book", new Book());

        return "addBook";
    }

    @RequestMapping(value = "addBook", method = RequestMethod.POST)
    public String addBook( @ModelAttribute("user") @Valid ValidationField validationField, Book book, BindingResult result) {
        /*this.user(book, result);*/

        if (result.hasErrors()) {
            return "addBook";
        }
        this.bookService.addBook(book);

        return "redirect:/";
    }
}

验证Class

public class ValidationField {

    @Size(min = 1, max = 3)
    private String name;

    @Size(min = 1, max = 3)
    private String genre;
}

并查看 addBook.jsp

<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<t:tamplate>
  <form:form method="post" action="addBook" commandName="book" modelAttribute="user">
      <form:errors path="*" cssClass="alert alert-danger" element="div" />
        <table>
            <tr>
                <td><form:input path="name"/></td>
                <td><form:errors path="name"/></td>
            </tr>
            <tr>
                <td><form:input path="genre" /></td>
                <td><form:errors path="genre"/></td>
            </tr>
            <tr>
                <td colspan="2"> <input type="submit" value="add book"> </td>
            </tr>
        </table>
    </form:form>
</t:tamplate>

您应该将 BindingResult 设置为立即跟随您的 ModelAttribute,例如

public String addBook( @ModelAttribute("user") @Valid ValidationField validationField, BindingResult result, Book book)

检查文档的部分 http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-methods

Most arguments can be used in arbitrary order with the only exception of BindingResult arguments

并继续

The Errors or BindingResult parameters have to follow the model object that is being bound immediately as the method signature might have more that one model object and Spring will create a separate BindingResult instance for each of them