这是我想要实现的目标: 我有一个更新请求对象,允许用户进行部分更新。但我想仅在请求正文中验证该字段。否则,可以为null。为了实现这一点,我使用GroupSequenceProvider让Validator知道要验证的组。我在这做错了什么?如果有错误,我该如何解决?
@GroupSequenceProvider(UpdateUserRegistrationGroupSequenceProvider.class)
public class UpdateUserRegistrationRequestV1 {
@NotBlank(groups = {EmailExistsInRequest.class})
@Email(groups = {EmailExistsInRequest.class})
@SafeHtml(whitelistType = SafeHtml.WhiteListType.NONE, groups = {EmailExistsInRequest.class})
private String email;
@NotNull(groups = {PasswordExistsInRequest.class})
@Size(min = 8, max = 255, groups = {PasswordExistsInRequest.class})
private String password;
@NotNull(groups = {FirstNameExistsInRequest.class})
@Size(max = 255, groups = {FirstNameExistsInRequest.class})
@SafeHtml(whitelistType = SafeHtml.WhiteListType.NONE, groups = {FirstNameExistsInRequest.class})
private String firstName;
// THERE ARE GETTERS AND SETTERS BELOW
}
组序列提供者代码:
public class UpdateUserRegistrationGroupSequenceProvider implements DefaultGroupSequenceProvider<UpdateUserRegistrationRequestV1> {
public interface EmailExistsInRequest {}
public interface PasswordExistsInRequest {}
public interface FirstNameExistsInRequest {}
@Override
public List<Class<?>> getValidationGroups(UpdateUserRegistrationRequestV1 updateUserRegistrationRequestV1) {
List<Class<?>> defaultGroupSequence = new ArrayList<Class<?>>();
defaultGroupSequence.add(Default.class);
defaultGroupSequence.add(UpdateUserRegistrationRequestV1.class);
if(StringUtils.hasText(updateUserRegistrationRequestV1.getEmail())) {
defaultGroupSequence.add(EmailExistsInRequest.class);
}
if(StringUtils.hasText(updateUserRegistrationRequestV1.getPassword())) {
defaultGroupSequence.add(PasswordExistsInRequest.class);
}
if(StringUtils.hasText(updateUserRegistrationRequestV1.getFirstName())) {
defaultGroupSequence.add(FirstNameExistsInRequest.class);
}
return defaultGroupSequence;
}
}
我正在使用Spring MVC,所以这就是我的控制器方法的样子,
@RequestMapping(value = "/{userId}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void updateUser(@PathVariable("userId") Long userId,
@RequestBody @Valid UpdateUserRegistrationRequestV1 request) {
logger.info("Received update request = " + request + " for userId = " + userId);
registrationService.updateUser(userId, conversionService.convert(request, User.class));
}
现在的问题是,UpdateUserRegistrationGroupSequenceProvider.getValidationGroups方法中的参数“updateUserRegistrationRequestV1”为空。这是我在请求正文中发送的请求对象,我正在发送电子邮件字段。
我做错了什么?
答案 0 :(得分:0)
我也遇到了同样的问题,并希望能解决
您只需要检查对象为空并将所有条件放入其中即可。
public List<Class<?>> getValidationGroups(Employee object) {
List<Class<?>> sequence = new ArrayList<>();
//first check if the object is null
if(object != null ){
if (!object.isDraft()) {
sequence.add(Second.class);
}
}
// Apply all validation rules from default group
sequence.add(Employee.class);
return sequence;
}