更新 根据以下建议,我已经包括
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.1.Final</version>
</dependency>
还将方法签名更改为:
public String updateProducts(@Valid @ModelAttribute("updateProductsForm") BindingResult result, UpdateProductsForm updateProductsForm, ModelMap modelMap) {
结果是一个不同的异常:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.validation.BindingResult]: Specified class is an interface
我试图让Spring进入验证表单字段。我将Hibernate验证设置为依赖:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
然后在我的对象中,我有这个:
@javax.validation.constraints.NotNull
@javax.validation.constraints.Size(min=1,max=255)
在对象模型中我有:
@Column(
name = "description",
nullable = false
)
private String description;
最后,在控制器中我有:
public String updateProducts(
@Valid @ModelAttribute("updateProductsForm") UpdateProductsForm updateProductsForm,
ModelMap modelMap, BindingResult result) {
List<Product> products = (List<Product>) modelMap.get("products");
if (result.hasErrors()) {
modelMap.addAttribute("products", products);
modelMap.addAttribute("errors", result.getAllErrors());
return "updateProducts";
}
我已经尝试了我能想到的一切,但无论我做什么,我都会在运行时遇到这种异常。
ype Exception report
message Request processing failed; nested exception is
org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction;
nested exception is javax.persistence.RollbackException: Error while committing the transaction
描述服务器遇到内部错误,导致无法完成此请求。如果我从Product对象中删除验证,一切正常(只是没有验证)。
例外:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
答案 0 :(得分:0)
您尚未设置仅验证jpa。您需要使用hibernate-validator进行验证。
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.1.Final</version>
</dependency>
是验证器的依赖项。
除此之外,BindingResult
必须直接遵循@ModelAttribute
带注释的属性,因此也要切换控制器方法中的ModelMap
和BindingResult
属性。