我收到以下验证异常。我之前在同一个问题上探索了一些答案,但对我没有任何帮助。
org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是 javax.validation.ConstraintViolationException: Validation failed for classes [com.rg.spring.model.User] during persist time for groups [javax.validation.groups.Default, ] 约束违规列表:[ ConstraintViolationImpl{interpolatedMessage='不能为空', propertyPath=fname, rootBeanClass=class com.rg.spring.model.User, messageTemplate='{org.hibernate.validator.constraints.NotEmpty.message}'} ] org.springframework.web.servlet。 FrameworkServlet.processRequest(FrameworkServlet.java:973) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
在我的模型中,我有
@NotEmpty
@Column(name = "fname", nullable = false)
String fname;
我有控制器
@RequestMapping(value = { "/new" }, method = RequestMethod.POST)
public String saveUser(@Valid User user, BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "registration";
}
service.saveUser(user);
model.addAttribute("success", "User " + user.getFname() + " registered successfully");
return "success";
}
我有以下messages.properties
NotEmpty.user.fname = First Name is required!
在 pom 中添加了以下依赖项
<!-- jsr303 validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.3.Final</version>
</dependency>
以下是 UI 表单
<form:form method="POST" modelAttribute="user">
<form:input type="hidden" path="id" id="id"/>
<table>
<tr>
<td><label for="fname">First Name: </label> </td>
<td><form:input path="fname" id="fname"/></td>
<td><form:errors path="fname" cssClass="error"/></td>
</tr>
我有以下方法在 AppConfig 下加载消息
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}