本文介绍了验证 Spring 中的对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下控制器方法:

@RequestMapping(value="/map/update", method=RequestMethod.POST, produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseEntityWrapper updateMapTheme(
        HttpServletRequest request,
        @RequestBody @Valid List<CompanyTag> categories,
        HttpServletResponse response
        ) throws ResourceNotFoundException, AuthorizationException {
...
}

CompanyTag 是这样定义的:

CompanyTag is defined this way:

public class CompanyTag {
    @StringUUIDValidation String key;
    String value;
    String color;
    String icon;
    Icon iconObj;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }
   ...
}

问题是未触发验证,未验证 CompanyTag 列表,从未调用StringUUIDValidation"验证器.

The problem is that validation is not triggered, the CompanyTag list is not validated, the "StringUUIDValidation" validator is never called.

如果我删除列表并仅尝试发送单个 CompanyTag,即而不是:

If I remove the List and only try to send a single CompanyTag, i.e. instead of:

@RequestBody @Valid List<CompanyTag> categories,

使用:

@RequestBody @Valid CompanyTag category,

它按预期工作,因此显然 Spring 不喜欢验证事物列表(尝试使用数组,但也不起作用).

it works as expected, so apparently Spring does not like to validate lists of things (tried with array instead, that did not work either).

有人知道缺少什么吗?

推荐答案

我发现了另一种有效的方法.基本问题是您希望将列表作为服务的输入有效负载,但 javax.validation 不会验证列表,只会验证 JavaBean.诀窍是使用一个自定义的列表类,它既可以作为 List 又可以 作为 JavaBean 使用:

I found another approach that works. The basic problem is that you want to have a list as your input payload for your service, but javax.validation won't validate a list, only a JavaBean. The trick is to use a custom list class that functions as both a List and a JavaBean:

@RequestBody @Valid List<CompanyTag> categories

更改为:

@RequestBody @Valid ValidList<CompanyTag> categories

您的列表子类将如下所示:

Your list subclass would look something like this:

public class ValidList<E> implements List<E> {

    @Valid
    private List<E> list;

    public ValidList() {
        this.list = new ArrayList<E>();
    }

    public ValidList(List<E> list) {
        this.list = list;
    }

    // Bean-like methods, used by javax.validation but ignored by JSON parsing

    public List<E> getList() {
        return list;
    }

    public void setList(List<E> list) {
        this.list = list;
    }

    // List-like methods, used by JSON parsing but ignored by javax.validation

    @Override
    public int size() {
        return list.size();
    }

    @Override
    public boolean isEmpty() {
        return list.isEmpty();
    }

    // Other list methods ...
}

这篇关于验证 Spring 中的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 23:28