java - Spring 3,JSR-303(bean 验证)和验证集合

标签 java spring-mvc bean-validation

我有一个简单的 Foo 类,像这样说:

public class Foo {
    @NotNull
    private String bar;
    public String getBar(){ return bar; }
    public void setBar(String _bar){ this.bar = _bar; }
}

现在,我有一个 Controller REST 方法,它采用一个 Foos 数组(或集合),我想确保每个 Foo 都有一个非空的 bar 属性。 我认为使用 @Valid 注释可以解决问题,但似乎并非如此:

@Controller
public class MyController {
    @RequestMapping(value="/foos", method=RequestMethod.POST)
    public @ResponseBody String createFoos(@Valid @RequestBody Foo[] foos){
        // blah blah blah
        return "yeah";
    }
}

注意:它也不适用于 List。但是有了一个独特的 Foo 它就可以了!

当我们有“多个”对象(在集合或数组中)时,Spring 验证似乎不起作用。

我什至尝试使用自定义注释实现 HandlerMethodArgumentResolver,但我不知道如何在 BindingResult 中定义“索引属性名称”。

如果有人知道这个问题的解决方法,将不胜感激! :)

最佳答案

我认为您在实现过程中遗漏了几件事。您需要使用对象图的概念来完成这项工作。

您的 Foo 类在其字段之一上进行了@NotNull 验证,但是您还没有真正表达需要对集合有效的内容。

来自 Hibernate 引用:

Object graph validation also works for collection-typed fields. That means any attributes that are arrays, implement java.lang.Iterable (especially Collection, List and Set) or implement java.util.Map can be annotated with @Valid, which will cause each contained element to be validated, when the parent object is validated.

所以你的代码会变成

@Controller
public class MyController {
    @RequestMapping(value="/foos", method=RequestMethod.POST)
    public @ResponseBody String createFoos(@Valid @NotNull @RequestBody Foo[] foos){
        // blah blah blah
        return "yeah";
    }
}

关于java - Spring 3,JSR-303(bean 验证)和验证集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8828457/

相关文章:

java - 如何使用 Hibernate 和 JPA 定义外键映射的字段顺序?

java - 使用 Freemarker 创建您自己的自定义助手?

jackson - 休眠验证器和 jackson : Using the @JsonProperty value as the ConstraintViolation PropertyPath?

java - 使用 Spring AOP 拦截特定注解

Java:比较两个音频文件看它们是否相同 "music"

java - 列表连接到数据库不显示数据JSP

java - 在Java中如何将 "block of memory"与 "objects"联系起来?

java - 使用 Hibernate 和 Spring MVC 在级联上保存包

java - 在 Fitnesse 测试中检索 applicationContext

spring-boot - Spring Boot jsr 303 嵌套数组路径验证失败