如何在 Spring 3.x 中使用 Hibernate @Valid 约束?
-
21-09-2019 - |
题
我正在研究简单的表单来验证这样的字段。
public class Contact {
@NotNull
@Max(64)
@Size(max=64)
private String name;
@NotNull
@Email
@Size(min=4)
private String mail;
@NotNull
@Size(max=300)
private String text;
}
我也在我的类路径上提供了 getter 和 setters hibernate 依赖项。但是我仍然不知道如何验证简单的表单,实际上没有那么多关于 spring hibernate 组合的文档。
@RequestMapping(value = "/contact", method = RequestMethod.POST)
public String add(@Valid Contact contact, BindingResult result) {
....
}
除了原始的 spring 3.x 文档之外,您能否解释一下或提供一些教程
解决方案
如果您想使用 @Valid 注释来触发支持 bean 的验证。那么它不是 Hibernate 注释,而是来自验证 API 的 javax.validation.Valid 。
要让它运行,你需要 两个都:
- Hibernate Validator 4.1.0 或更高版本 (从这里下载: http://sourceforge.net/projects/hibernate/files/hibernate-validator)
- bean验证API(从这里下载: http://repository.jboss.org/maven2/javax/validation/validation-api/1.0.0.GA/
就我而言,我使用自定义验证器 (RegistrationValidator),而不是在支持 bean 中注释表单字段来进行验证。我需要为错误消息设置 I18N 键,这就是我必须用我自己的 MessageCodeResolver 替换 Spring 3 MessageCodeResolver 的原因。当第一种方式找不到时,Spring 3 中的原始版本总是尝试添加类型或字段名称来查找正确的键。
一个小例子:
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
...
import javax.validation.Valid;
@Controller
public class RegistrationController
{
@InitBinder
protected void initBinder(WebDataBinder binder)
{
binder.setMessageCodesResolver(new MessageCodesResolver());
binder.setValidator(new RegistrationValidator());
}
@RequestMapping(value="/userRegistration.html", method = RequestMethod.POST)
public String processRegistrationForm(@Valid Registration registration, BindingResult result, HttpServletRequest request)
{
if(result.hasErrors())
{
return "registration"; // the name of the view
}
...
}
}
所以希望这会有所帮助。
顺便提一句。如果有人知道 Bean Validation API 的官方网页,请告诉...谢谢。
其他提示
我知道这个人是回答......但这里是我的0.02 $值得反正:-)我曾用同样的例子布拉克指,和验证也没有被自动调用......我不得不添加在<mvc:annotation-driven />
我的应用程序上下文文件...(然后验证被触发)。请确保您还MVC的详细信息添加到架构声明...例子如下...
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/mvc
">
<mvc:annotation-driven />
...
</beans>
不隶属于 StackOverflow