解决@Valid 校验List参数无效的问题

如下代码中使用@Valid注解校验List<CreateWaybillDTO>类型参数waybillDTOS

    @ApiOperation("新建运单")
    @PostMapping(value = "createWaybill" + Constant.POST_JSON)
    @ApiResponse(code = 200, message = "创建成功", response = ResponseEntity.class)
    public ResponseEntity<BaseDTO> createWaybill(@RequestBody @Valid List<CreateWaybillDTO> waybillDTOS) {
        return new ResponseEntity(new BaseDTO("200", "创建成功"), HttpStatus.OK);
    }

校验参数如下

    // 运单id
    @ApiModelProperty("运单id")
    @NotNull
    @Min(value = 1, message = "运单id不合法")
    private int waybillId;
    // 进口出口
    @ApiModelProperty("进口出口")
    @NotNull
    private int importAndExport;

调用参数如下


[  
   {  
     "arrivalTime": "string",  
     "bookingPerson": "string",  
     "bookingPersonType": "string",  
     "bookingSpacePrice": "string",  
     "boxDTOList": [  
       {  
         "boxId": 0,  
         "boxNumber": "string",  
         "boxType": "string",  
         "cargoWeight": "string",  
         "goodsName": "string",  
         "leadSealNumber": "string"  
       }  
     ],  
     "boxRemarks": "string",  
     "contactAddress": "string",  
     "contactFullName": "string",  
     "contactPerson": "string",  
     "contactPhone": "string",  
     "contactPoint": "string",  
     "customerSignsReceipt": "string",  
     "dangerousGoodsCategory": "string",  
     "dangerousGoodsIdentification": "string",  
     "dangerousGoodsNumber": "string",  
     "dangerousGoodsRemarks": "string",  
     "departurePort": "string",  
     "destinationPort": "string",  
     "emptyBoxGoods": "string",  
     "financialWithholdingGoods": "string",  
     "freightCollection": "string",  
     "imdgr": "string",  
     "importAndExport": 0,  
     "internalRemarks": "string",  
     "packingTime": "string",  
     "paymentMethod": "string",  
     "remarks": "string",  
     "shipName": "string",  
     "specialRequirements": "string",  
     "voyage": "string",  
     "waybillId": 0,  
     "waybillNo": "string",  
     "withholdingGoods": "string"  
   }  
 ]

返回结果如下

{
  "id": null,
  "backcode": "200",
  "backmsg": "创建成功"
}

我们校验waybillId最小值是1,传入参数的值是0,但是确拿到了校验通过的结果
解决方法:
新建一个类实现List接口,并实现对应方法,如下

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

    @Valid
    private List<E> list = new ArrayList<>();

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

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

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

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

    @Override
    public boolean contains(Object o) {
        return list.contains(o);
    }

    @Override
    public Iterator<E> iterator() {
        return list.iterator();
    }

    @Override
    public Object[] toArray() {
        return list.toArray();
    }

    @Override
    public <T> T[] toArray(T[] a) {
        return list.toArray(a);
    }

    @Override
    public boolean add(E e) {
        return list.add(e);
    }

    @Override
    public boolean remove(Object o) {
        return list.remove(o);
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        return list.contains(c);
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {
        return list.addAll(c);
    }

    @Override
    public boolean addAll(int index, Collection<? extends E> c) {
        return list.addAll(index, c);
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        return list.removeAll(c);
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        return list.retainAll(c);
    }

    @Override
    public void clear() {
        list.clear();
    }

    @Override
    public E get(int index) {
        return list.get(index);
    }

    @Override
    public E set(int index, E element) {
        return list.set(index, element);
    }

    @Override
    public void add(int index, E element) {
        list.add(index, element);
    }

    @Override
    public E remove(int index) {
        return list.remove(index);
    }

    @Override
    public int indexOf(Object o) {
        return list.indexOf(o);
    }

    @Override
    public int lastIndexOf(Object o) {
        return list.lastIndexOf(o);
    }

    @Override
    public ListIterator<E> listIterator() {
        return list.listIterator();
    }

    @Override
    public ListIterator<E> listIterator(int index) {
        return list.listIterator(index);
    }

    @Override
    public List<E> subList(int fromIndex, int toIndex) {
        return list.subList(fromIndex, toIndex);
    }
}

我们将接口修改成如下
List<CreateWaybillDTO>修改为ValidList<CreateWaybillDTO>我们刚刚新建的实现类

    @ApiOperation("新建运单")
    @PostMapping(value = "createWaybill" + Constant.POST_JSON)
    @ApiResponse(code = 200, message = "创建成功", response = ResponseEntity.class)
    public ResponseEntity<BaseDTO> createWaybill(@RequestBody @Valid ValidList<CreateWaybillDTO> waybillDTOS) {
        return new ResponseEntity(new BaseDTO("200", "创建成功"), HttpStatus.OK);
    }

同样的参数调用这个接口返回结果如下

{
  "timestamp": "2019-05-08",
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.bind.MethodArgumentNotValidException",
  "errors": [
    {
      "codes": [
        "Min.createWaybillDTOList.list[0].waybillId",
        "Min.createWaybillDTOList.list.waybillId",
        "Min.list[0].waybillId",
        "Min.list.waybillId",
        "Min.waybillId",
        "Min.int",
        "Min"
      ],
      "arguments": [
        {
          "codes": [
            "createWaybillDTOList.list[0].waybillId",
            "list[0].waybillId"
          ],
          "arguments": null,
          "defaultMessage": "list[0].waybillId",
          "code": "list[0].waybillId"
        },
        1
      ],
      "defaultMessage": "运单id不合法",
      "objectName": "createWaybillDTOList",
      "field": "list[0].waybillId",
      "rejectedValue": 0,
      "bindingFailure": false,
      "code": "Min"
    }
  ],
  "message": "Validation failed for object='createWaybillDTOList'. Error count: 1",
  "path": "/web/WaybillPush/createWaybill.json"
}

问题解决

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 11,169评论 6 13
  • CloudJavaBackendSummaries1、开发环境eclipse工程,引入jw仓库的jw-base,3...
    燕京博士阅读 1,147评论 0 0
  • JAVA面试题 1、作用域public,private,protected,以及不写时的区别答:区别如下:作用域 ...
    JA尐白阅读 1,183评论 1 0
  • width: 65%;border: 1px solid #ddd;outline: 1300px solid #...
    邵胜奥阅读 4,887评论 0 1
  • 人生如果能重头,再不会放弃您的温柔!谁曾想岁月悠悠,多少美梦已付诸东流。而今孤立深秋,斩不断的思绪又...
    爱粉阅读 346评论 2 6