简体   繁体   中英

Custom validation in spring MVC

i want to implement custom validation for my entity. here is my entities. in fact i want to validate baskets object and when it null remove from list. when i run code this error occur. Bean property 'comment' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?

public class TypistData {
  private List<BasketData> baskets;
  private DateData orderDate;

  //getter and setter
}

public class BasketData {
 private HashedLong id;
 private CustomerData customer;
 private Long discount;
 private String comment;
 private HashedLong region;
 private List<OrderData> orders;

 //getter and setter
}

and my custom validation is

  public class TypistDataValidation implements Validator {
@Override
public boolean supports(Class<?> aClass) {
    return aClass.isAssignableFrom(TypistData.class);
}

@Override
public void validate(Object o, Errors errors) {
    TypistData typistData = (TypistData)o;
    List<BasketData> basketDatas = typistData.getBaskets();

    if(typistData.getOrderDate()== null
        errors.rejectValue("orderDate","orderDate","can not be null");
    for(BasketData data:basketDatas){
        if(!isEmpty(data)){
            validateBasket(data,errors);
        } else basketDatas.remove(data);
    }
}

private boolean isEmpty(BasketData basketData){
    if(basketData.getCustomer()== null && basketData.getOrders().size()==0
                                       && basketData.getComment()== null
                                       && basketData.getDiscount()==null
                                       && basketData.getRegion()==null)
        return true;
    return false;

}
private void validateBasket(BasketData basketData,Errors errors){
    if(basketData.getRegion() == null)
        errors.rejectValue("region","can not be null");
     if(basketData.getDiscount()== null)
        errors.rejectValue("discount","can not be null");
    if(basketData.getComment() == null)
        errors.rejectValue("comment","can not be null");
    if(basketData.getOrders().size() == 0)
        errors.rejectValue("orders","can not be null");
    if(basketData.getCustomer() == null)
        errors.rejectValue("customer","can not be null"); 
}

}

In your BasketData class you should have a getter method for field comment.

public String getComment() {
      return this.comment;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM