我的 Spring boot 项目中有以下实体类:
@Entity
@Table(name="user_account_entity")
@JsonDeserialize(using = UserAccountDeserializer.class)
public class UserAccountEntity implements UserDetails {
private final static String ROLE_USER = "ROLE_USER";
@Id
@NotBlank
private String id;
@NotBlank(message="Username cannot be empty")
@Email(message="Username must be a valid email address")
private String username;
@NotBlank(message="Password cannot be empty")
@Password
private String password;
@NotNull
@MapsId
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private UserEntity user;
public UserAccountEntity(final String username, final String password) {
this.password = password.trim();
this.username = username.trim();
}
public UserAccountEntity() {}
//setters and getters
}
和以下 Controller :
@RequestMapping("/api/authentication")
public class UserAccountControllerImpl implements UserAccountController {
@Autowired
private UserAccountService userAccountService;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public String create(@RequestBody UserAccountEntity userAccount,
HttpServletResponse response) {
String username = userAccount.getUsername();
String password = userAccount.getPassword();
UserEntity user = new UserEntity();
UserAccountEntity userAccount = new UserAccountEntity(username,
passwordEncoder.encode(password));
userAccount.setUser(user);
userAccountRepository.save(userAccount);
return userAccountService.authenticateUserAndSetResponsenHeader(
username, password, response);
}
}
如您所见,我有一个字段密码
的自定义 validator :
public class PasswordValidator implements ConstraintValidator<Password, String> {
public void initialize(Password constraintAnnotation) {}
public boolean isValid(String value, ConstraintValidatorContext context) {
String trimmedValue = value.trim();
if (trimmedValue.length() > 30 || trimmedValue.length() < 8) {
return false;
}
if (!Pattern.compile( "[0-9]" ).matcher(trimmedValue).find()) { // it doesn't contain any digit
return false;
}
if (trimmedValue.toUpperCase().equals(trimmedValue)) { //it's all upper-case
return false;
}
if (trimmedValue.toLowerCase().equals(trimmedValue)) { //it's all lower-case
return false;
}
return true;
}
}
如何验证 Controller 中请求正文中的 password
字段,但在保存时不验证?当我在保存时对该字段进行编码时,保存时验证不会通过。
最佳答案
第一步是在请求正文上使用@Valid
。因此,新的代码更改将如下所示:
@Override
public String create (@Valid @RequestBody UserAccountEntity userAccount,
HttpServletResponse response) {
...
}
此后,您可以使用 InitBinder
绑定(bind)您的自定义 validator :
@InitBinder
public void binder(WebDataBinder binder) {
binder.addValidator(new PasswordValidator());
}
请注意,标有 @InitBinder
的方法是 Controller
类的一部分。
关于java - 验证 Controller 上的字段(作为请求正文),但不将其保存在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52491232/