|
|
|
package ${basePackage}.frame.utils;
|
|
|
|
|
|
|
|
import ${basePackage}.frame.base.BaseRequest;
|
|
|
|
import ${basePackage}.frame.base.BaseResponse;
|
|
|
|
import ${basePackage}.frame.base.ErrorType;
|
|
|
|
|
|
|
|
import javax.validation.ConstraintViolation;
|
|
|
|
import javax.validation.Validation;
|
|
|
|
import javax.validation.Validator;
|
|
|
|
import javax.validation.ValidatorFactory;
|
|
|
|
import java.util.ArrayList;
|
|
|
|
import java.util.List;
|
|
|
|
import java.util.Set;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 验证工具类。提供一些通用简单的数据验证功能
|
|
|
|
*
|
|
|
|
* @author wangbing
|
|
|
|
* @version 0.0.1
|
|
|
|
* @since 2017-01-01
|
|
|
|
*/
|
|
|
|
public class ValidationUtil {
|
|
|
|
|
|
|
|
private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
|
|
|
|
|
|
|
|
public static <T extends BaseResponse> T validate(BaseRequest req, T response) {
|
|
|
|
|
|
|
|
if (req == null) {
|
|
|
|
response.addError(ErrorType.EXPECTATION_NULL, "请求对象不能为空");
|
|
|
|
return response;
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
Validator validator = factory.getValidator();
|
|
|
|
|
|
|
|
Set<ConstraintViolation<BaseRequest>> constraintViolations = validator.validate(req);
|
|
|
|
|
|
|
|
if (constraintViolations.size() > 0) {
|
|
|
|
for (ConstraintViolation<BaseRequest> violation : constraintViolations) {
|
|
|
|
response.addError(ErrorType.INVALID_PARAMETER, violation.getMessage());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} catch (Exception e) {
|
|
|
|
e.printStackTrace();
|
|
|
|
LogUtil.dumpException(e);
|
|
|
|
response.addError(ErrorType.BUSINESS_ERROR, e.getMessage());
|
|
|
|
}
|
|
|
|
return response;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static List<String> validate(Object req) {
|
|
|
|
List<String> validResult = new ArrayList<>();
|
|
|
|
if (req == null) {
|
|
|
|
validResult.add("当前数据为空");
|
|
|
|
return validResult;
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
Validator validator = factory.getValidator();
|
|
|
|
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(req);
|
|
|
|
if (constraintViolations.size() > 0) {
|
|
|
|
for (ConstraintViolation<Object> violation : constraintViolations) {
|
|
|
|
validResult.add(violation.getMessage());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} catch (Exception e) {
|
|
|
|
e.printStackTrace();
|
|
|
|
validResult.add("数据检查错误");
|
|
|
|
}
|
|
|
|
return validResult;
|
|
|
|
}
|
|
|
|
}
|