javax中验证Violation

今天稍微研究了一下@Size @NotNull是怎么使用的。

使用简单总结

  1. 在属性上使用@Size等

  2. 如果属性又被封装了一次,需要在封装后的类(当为方法中的参数时)前添加@Valid注解。

  3. 在要验证的方式的方法会类上使用@Validated注解。

  4. 如果不符合验证要求则会抛出ConstraintViolationException异常。我们可以从此异常中获取信息。

例子

使用@NotNull
@Setter
@Getter
@ToString
public class InCheckGood implements Serializable{

    private static final long serialVersionUID = 7380187610657543155L;

    @NotNull(message = "requestSn不可以为空!")
    private String requestSn; //批次号
    @NotNull(message = "applicationId不可以为空!")
    private String applicationId; //应用id
    private Integer requestType;//请求类型  1 上架,2 下单,3 提货
    private Integer operatorId;//请求人id
    private String operatorName;//请求人名字
    @NotNull(message = "goodId不可以为空!")
    private String goodId;//货物id
    @NotNull(message = "packageType不可以为空!")
    private Integer packageType; //捆包类型  10 实捆包 20 虚捆包
    @NotNull(message = "storagePlaceCode不可以为空!")
    private String storagePlaceCode;//仓库编码
    private String storagePlaceName;//仓库名称
    private Integer providerId;//货主
    private String providerName;//货主名称
    private String packCode;//捆包号
    private String productTypeCode;//大品名码
    private String productTypeName;// 大品名名称
    private String productCode; //小品名码
    private String productName;//(小)品名
    private String shopSign;//牌名
    private Double weight;//(总)重量
    private Double length;
    private Double width;
    private Double thick;//厚度
    private Double diameter;//直径
    private String productOrignCode;//产地(钢厂)码
    private String productOrignName;//产地名
    private Integer pieces;//件数


}
使用@Valid 和@Validated
@Service
@Validated
public class ThirdSystemBiz {
  public List<OutCheckGoodVo> checkGood(@Valid List<InCheckGood> inCheckGoods) throws Exception {
    ...
  }
}
调用方法
 public CheckGoodReturnVo checkGoods(@RequestBody Dr<InCheckGoodRequest> dr) {

        ...
        try{
           ...
            outCheckGoodVos = thirdSystemBiz.checkGood(inCheckGoods);
            resultVo.setReturnCode(WarehouseConstant.CHECK_GOOD_SUCCESS);
           ...
        }catch (ConstraintViolationException e2){
           ...
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("参数出错:");
            for (ConstraintViolation<?> constraintViolation : e2.getConstraintViolations()) {
                stringBuffer.append(constraintViolation.getMessage()).append(";");
            }
            resultVo.setReturnMsg(stringBuffer.toString());
           ...
        }catch (Sv2Exception e1){
            ...
        }catch (Exception e){
            ...
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值