Spring MVC 提供了两种数据校验的方式:
package com.southwind.entity;
import lombok.Data;
@Data
public class Account {
private String name;
private String password;
}
package com.southwind.validator;
import com.southwind.entity.Account;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class AccountValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Account.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmpty(errors,"name",null,"姓名不能为空");
ValidationUtils.rejectIfEmpty(errors,"password", null,"密码不能为空");
}
}
package com.southwind.validator;
import com.southwind.entity.Account;
import org.springframework.validation.Errors