【发布时间】:2017-11-01 09:12:03
【问题描述】:
我正在尝试使用 Hibernate Validator 制作简单的验证表单。我的客户类中有两个字段,我希望其中一个是必需的(姓氏)。 关键是,即使我没有填写此字段,我也没有收到错误消息,并且 BindingResult 不包含任何错误。我的代码中是否缺少任何内容?
这是我的客户类 sn-p。
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: 我添加到类路径validation-api.jar(包含抽象API和注释扫描器)。
还插入了@InitBinder,只是为了确保空表单字段始终为空而不是空字符串。
@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) 这样的提供程序添加到您的类路径中。
虽然我已经将它添加到类路径中
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-validation-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.LocalValidatorFactoryBean"/>
我的类路径中还有 Hibernate Validator:
但错误仍然存在
【问题讨论】:
-
那么,客户姓氏的值是多少?它的长度是多少?
-
我没有在我的表单中给出任何价值。所以长度为0。
-
你认为它是0,还是你知道它是0,因为你打印了
theCustomer.getLastName().length()的值并且输出是0?您是否按照此处的说明启用了验证:docs.spring.io/spring/docs/current/spring-framework-reference/…? -
你的类路径上有 hibernate-validator-annotation-processor 吗?
-
检查该值是否真的为 null 或空字符串。 @NotBlank 可能是这里更合适的验证器。