Hibernate Validator @NotNull无法正常工作

时间:2017-11-01 09:12:04

标签: java spring hibernate

我正在尝试使用Hibernate Validator创建简单的验证表单。我的Customer类中有两个字段,我希望其中一个是必需的(lastName)。 关键是即使我没有填写此字段,我也没有收到错误消息,BindingResult不包含任何错误。我的代码中是否有任何遗漏?

这是我的Customer类代码段。

public class Customer {

    private String firstName;

    @NotNull(message = "is required")
    @Size(min = 1, message = "is required")
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

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

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

这是控制器

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

    //adding new customer to model
    @RequestMapping("/showForm")
    public String showForm(Model theModel){

        theModel.addAttribute("customer", new Customer());

        return "customer-form";
    }

    //Validating passed customer attribute/object
    //Biding result object holds validation results
    @RequestMapping("/processForm")
    public String processForm(
            @Valid @ModelAttribute("customer") Customer theCustomer, BindingResult theBindingResult) {

        if (theBindingResult.hasErrors()){
            return "customer-form";
        }

        return "customer-confirmation";
    }
}

编辑:表单代码:

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

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Customer Registration Form</title>
</head>
<body>

<style>
    .error{color: red}
</style>


<i> Fill out the form. Asteriks (*) means required. </i>
<br><br>
<form:form action="processForm" modelAttribute="customer">

    First name: <form:input path="firstName" />

    <br><br>

    Last name (*): <form:input path="lastName"/>
    <form:errors path="lastName" cssClass="error" />
    <input type="submit" value="Submit"/>

</form:form>

</body>
</html>

编辑2: 我添加到classpath validation-api.jar(包含抽象API和注释扫描程序)。

还插入了@InitBinnder,以确保空表单字段始终为null而不是空字符串。

@InitBinder
public void initBinder(WebDataBinder dataBinder) {

    StringTrimmerEditor stringTrimmerEditor = new StringTrimmerEditor(true);

    dataBinder.registerCustomEditor(String.class, stringTrimmerEditor);
}

但似乎这些注释似乎永远不会被触发

编辑3:在实体上调用验证器后,我收到错误:

org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是javax.validation.NoProviderFoundException:无法创建配置,因为找不到Bean验证提供程序。将类似Hibernate Validator(RI)的提供程序添加到类路径中。

虽然我已将其添加到classpath

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
validator.validate(theCustomer);

编辑4:添加Spring配置文件:

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">

    <display-name>mvc-validation-demo</display-name>

    <!-- Spring MVC Configs -->

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mvc-validation-demo.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

MVC验证-demo.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/">

    <context:component-scan base-package="com.lobo.mvc" />

    <mvc:annotation-driven/>

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

编辑5:根据@eis所说的我添加到我的mvc-validation-demo.xml中:

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalVa‌​lidatorFactoryBean"/‌​>

我的类路径中也有Hibernate Validator:

Classpath

但错误仍然存​​在

1 个答案:

答案 0 :(得分:0)

删除.idea,清除缓存和新配置为我完成了这项工作。看来它似乎没有看到hibernate-validator.jar。

感谢所有贡献者。