這是很簡單的,我們可以重用在Spring數據休息事件MVC驗證。例如,如果我想在保存前驗證用戶口令,我會在下面的代碼添加到保存之前的事件 -
@Autowired
PasswordValidator passwordValidator;
@HandleBeforeSave
public void beforeUsersave(User user) {
PasswordDTO passwordDTO = new PasswordDTO(user.getPassword(), user.getMatchingPassword());
Errors errors = new BeanPropertyBindingResult(passwordDTO, "user");
passwordValidator.validate(passwordDTO, errors);
if (errors.hasErrors()) {
throw new RepositoryConstraintViolationException(errors);
}
}
我使用同樣的PasswordValidator在我更改密碼呼叫MVC驗證。
這裏是我的PasswordValidator
package org.amnesty.cms.domain.validation;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PasswordValidator implements Validator {
public boolean supports(Class clazz) {
return PasswordDTO.class.equals(clazz);
}
private Pattern pattern;
private Matcher matcher;
private static final String passwordRegex = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=\\S+$).{8,50}$";
public PasswordValidator() {
pattern = Pattern.compile(passwordRegex);
}
public void validate(Object passwordObj, Errors errors) {
PasswordDTO passwordDTO = (PasswordDTO) passwordObj;
String password = passwordDTO.getPassword();
ValidationUtils.rejectIfEmpty(errors, "password", "password", "Password can't be null or empty");
if (!StringUtils.isEmpty(password)) {
if (password.length() < 8) {
errors.rejectValue("password", "password", "Password length should be at least 8 characters");
}
if (password.length() > 50) {
errors.rejectValue("password", "password", "Password length can't be more than 50 characters");
}
}
if (!errors.hasErrors()) {
matcher = pattern.matcher(password);
if (!matcher.matches()) {
errors.rejectValue("password", "password", "Invalid password. A valid password contains at least " +
"one digit, one lowercase character, one uppercase character and no whitespace");
}
}
if (!errors.hasErrors() && !password.equals(passwordDTO.getMatchingPassword())) {
errors.rejectValue("matchingPassword", "matchingPassword", "Matching password is different from password");
}
}
}
是否足夠驗證輸入參數的控制器方法? – John
將會有兩個區域進行輸入驗證,從而增加維護。我正在考慮在一個地方爲MVC服務和休息實體進行驗證。 – user1045445