SpringMVC參數校驗之校驗集合中的字段


/**
 * @author Yangqi.Pang
 */
@RestController
@RequestMapping("/warehouse")
public class WarehouseAllocateController {

    @Autowired
    private WarehouseShipperService warehouseShipperService;


    @PostMapping("/allocate")
    public ApiResult<Object> allocate(@RequestBody AllocationReq allocationReq){
        //TODO 分倉規則
        return ApiResult.success();
    }

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class AllocationReq {

        /**
         * 收貨貨主編號
         */
        private String storeShipperCode;

        /**
         * 發貨貨主編號
         */
        private String deliverShipperCode;

        /**
         * 訂單類型
         */
        @NotNull(message = "訂單類型")
        private OrderType orderType;

        /**
         * 貨品明細
         */
        @NotEmpty(message = "貨品明細不能為空")
        private List<GoodsDetail> goodsDetails;

    }

    @Getter
    @AllArgsConstructor
    public enum OrderType {

        /**
         * 入庫單
         */
        STORE,

        /**
         * 出庫單
         */
        DELIVER,

        /**
         * 調撥單
         */
        TRANSFER
    }

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class GoodsDetail {

        /**
         * 貨主貨品編碼
         */
        @NotBlank(message = "貨主貨品編碼不能為空")
        private String shipperGoodsCode;

        /**
         * 批次號
         */
        private String batchNo;

        /**
         * 數量
         */
        @NotNull(message = "數量不能為空")
        private BigDecimal num;
    }
}

  如代碼所示:如何在Controller層校驗goodsDetails 所傳的參數?

1.Controller層加@Validated注解

 

走單元測試校驗參數:

public class WarehouseAllocateControllerTest extends BaseTest {

    @Autowired
    private WarehouseAllocateController warehouseAllocateController;

    @Test
    @DisplayName("分倉規則傳參校驗單元測試")
    public void testValidate(){
        WarehouseAllocateController.AllocationReq allocationReq = WarehouseAllocateController.AllocationReq.builder()
                .build();
        warehouseAllocateController.allocate(allocationReq);
    }

}

 校驗結果:

 

 

 

我沒有傳參數,但是校驗通過了,說明校驗不起做用

2.方法層加@Validated 

 

 校驗結果:

 

 還是能通過,說明校驗還是不起作用

2.方法層加@Vaild

 

 校驗結果:

 

 

校驗不通過,說明校驗有效

 

3.單元測試增加參數

 

 校驗結果:

 

 校驗通過,但有個問題是,我只是傳了一個空的對象,沒有校驗集合里面的對象的屬性:

 

 4.對象集合屬性上加@Valid

 

 校驗結果:

 

 校驗不通過,說明校驗有作用

 

總結:如果校驗的對象是集合,而且還要校驗的是集合里面的每個對象的屬性時,就可以采用此種方式:Controller層加@Validated,方法層加@Valid, 集合屬性上加@Valid 就可以實現完整校驗;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM