java - 验证 Controller 上的字段(作为请求正文),但不将其保存在数据库中

标签 java spring

我的 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/

相关文章:

java - 当关键代码语句中未实现日志记录时,更好的调试方法

Java for循环索引: "j" isn't starting at the begining of my char Array after one loop of my index : "i"

java - 非法 block 大小异常 : Input length must be multiple of 8 when decrypting with padded cipher

java - 方法预期通过比较器比较两个字段,但仅按 1 排序

spring boot rest外部tomcat 401错误

java - Spring - 在调用 Controller 的方法之前执行代码

java - AbstractUserTypeHibernateIntegrator 用户类型的 Hibernate 空指针

java - 如何在订阅/取消订阅时执行 Completable

java - 将简单的 AppEngine Java 项目转换为使用模块

spring - application.yml 中的环境变量不适用于以空格开头的默认值