3

我正在使用简单的表单来验证像这样的字段。

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 和 setter hibernate 依赖项。但是我仍然不知道如何验证简单的表单,实际上没有太多关于 spring hibernate 组合的文档。

@RequestMapping(value = "/contact", method = RequestMethod.POST)
public String add(@Valid Contact contact, BindingResult result) {
    ....
}

您能否解释一下或提供一些教程,除了原始 spring 3.x 文档

4

3 回答 3

7

如果您想使用 @Valid 注释来触发对您的支持 bean 的验证。那么它不是 Hibernate 注释,它是来自验证 API 的 javax.validation.Valid 。

要使其运行,您需要两者

在我的例子中,我使用了一个自定义验证器(RegistrationValidator),而不是在支持 bean 中注释表单字段来进行验证。我需要为错误消息设置 I18N 键,这就是我必须用我自己的替换 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 的官方网页,请告诉... 谢谢。

于 2010-08-10T21:38:36.397 回答
7

<mvc:annotation-driven /> 我知道这个问题得到了回答……但无论如何,这是我价值 0.02 美元的 :-) 我使用了 Burak 所指的相同示例,并且验证也没有被自动调用……我不得不将应用程序上下文文件...(然后触发验证)。确保您还将 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>
于 2011-03-22T09:34:10.780 回答
0

http://blog.springsource.com/2009/11/17/spring-3-type-conversion-and-validation/

于 2010-01-10T11:40:46.487 回答