BindingResult 对象没有错误

BindingResult object has not errors

我有以下代码

对象

package com.example.demo;
import javax.validation.constraints.*;

public class Customer {

    @NotEmpty(message="first name should contain a value")
    private String firstName;
    
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    
}

控制器

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.validation.BindingResult;
import javax.validation.Valid;

@Controller
@RequestMapping("/customer")
public class CustomerController {

    private static int counter = 0;

 
    @RequestMapping("/showForm")
    public String showForm(Model model) {
        model.addAttribute("customer", new Customer());
        return "customer-form";
    }

    @RequestMapping("/processForm")
    public String processForm(@Valid @ModelAttribute("customer") Customer customer, BindingResult bindingResult) {
        return "customer-form";
    }

}

jsp 文件中的表单

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    <html>

    <head></head>

    <body>
        <form:form method="POST" action="processForm" modelAttribute="customer">
            <form:label path="firstName">Name</form:label>
            <form:input path="firstName" />
            <form:errors path="firstName"/>
            <button type="submit">Submit</button>
        </form:form>
    </body>

    </html>

我已经进行了一些调试,当我单击提交按钮时,方法 processForm 被正确调用,但 bindingResult 没有错误。 firstName 变量为空。为什么验证不起作用?

确保您已在 pom.xml 中声明了 Hibernate Validator 依赖项(如果您使用 maven)

<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>7.0.4.Final</version>
</dependency>

验证约束可以在其他库的类路径中,但验证处理器依赖于上面