springboot注解校验对象数据
1.方式一
import javax.validation.ConstraintViolation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import java.util.Set;
public class ValidUtils {
/**
* 实体类参数有效性验证
* @param bean 验证的实体对象
* @param groups 验证组
* @return 验证成功:返回true;验证失败:将错误信息添加到message中
*/
public static void validObject(Object bean, Validator validator, Class> ...groups) {
Set> constraintViolationSet = validator.validate(bean, groups);
if (!constraintViolationSet.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (ConstraintViolation violation: constraintViolationSet) {
sb.append(violation.getMessage());
}
throw new ValidationException(sb.toString());
}
}
}
//自动装配到工厂
import org.hibernate.validator.HibernateValidator;
@Configuration
@EnableAutoConfiguration
@Slf4j
public class DefaultCommonConfiguration {
@Bean
public Validator validator() {
ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
.configure()
.failFast( true )
.buildValidatorFactory();
Validator validator = validatorFactory.getValidator();
return validator;
}
}
public class OriginalRecord {
private @Valid BasicInfo basicInfo;
有其他对象的,
,
,
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Slf4j
public class BasicInfo {
@NotBlank(message = "id is not null")
@Size(max = 50, message = "id length cannot be greater than 50")
@SerializedName("id")
}
import javax.validation.Validator;
import javax.validation.groups.Default;
@RestController
@Slf4j
@RequestMapping(value = "/api/v1111")
public class testController {
@Resource
private Validator validator;
@RequestMapping(value = "访问路由")
public OrionResponse record( @RequestBody String originalBody) throws PassPermitException {
//验证第三方数据
ValidUtils.validObject(baseRecord, validator, Default.class);
return "要返回的对象";
}
}
2.方式二
@PostMapping(value = "/testModify")
public StatusResponse batchModify(@Validated @RequestBody ModifyTestRequest request, BindingResult bindResult) {
if (bindResult.hasErrors()) {
StringBuffer sb = new StringBuffer();
for (ObjectError err : bindResult.getAllErrors()) {
if (sb.length() > 0) {
sb.append(",");
}
sb.append(((FieldError) err).getField());
}
throw new TestPassException(PARAM_INVALID, "param error", sb.toString());
}
return "返回结果"
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ModifyTestRequest {
//对象用注解验证不能为空
@NotEmpty
private List codeIds;
具体其他验证规整可以参考验证的一些文档 ,,,
}