猿问

保存后验证器无效

此验证程序检查数据库中登录名的唯一性。在第一次检查时,即当他进入 counterlord 时,一切都很好。但它在保存到数据库时也有效。但不幸的是,负责检查登录唯一性的服务不能@Autowire。问题是什么?是否应该检查 2 次?


class ValidatorUniqueLogin : ConstraintValidator<UniqueLogin, String> {


    @Autowired val serviceAccaunt: ServiceAccaunt? = null // this null


    override fun initialize(annotation: UniqueLogin?) {}


    override fun isValid(login: String, ctx: ConstraintValidatorContext): Boolean {

        return serviceAccaunt!!.isHaveLogin(login)

    }

}



@Documented

@Constraint(validatedBy = [ValidatorUniqueLogin::class])

@Target(AnnotationTarget.FIELD)

@Retention(RetentionPolicy.RUNTIME)

annotation class UniqueLogin(

        val message: String = "{text.error.login.not.unique}",

        val groups: Array<KClass<*>> = [],

        val payload: Array<KClass<out Payload>> = []

)


@Service

class ServiceAccaunt(@Autowired val repoAccaunt: RepoAccaunt) {


    fun isHaveLogin(login: String): Boolean {

        val count = repoAccaunt.countByLogin(login)

        return !(count > 0)

    }


}


@IsAnonymous

    @PostMapping("/reg")

    fun reg(

            model: Model,

            @Valid @ModelAttribute("accaunt") accaunt: Accaunt,

            bindingResult: BindingResult

    ): String {


        if (accaunt.roles.isNotEmpty()) {

            val acessRoles = serviceRole.findRolesForRegistration()

            for (role: Role in accaunt.roles) if (!acessRoles.contains(role)) accaunt.roles.minus(role)

        }




白猪掌柜的
浏览 88回答 1
1回答

喵喵时光机

我不明白为什么会这样,并决定发布第二次验证。最后,一切正常。为什么spring要验证几次我没看懂,但是我觉得这段代码在实现上还是挺有效的。class ValidatorUniqueLogin : ConstraintValidator<UniqueLogin, String> {&nbsp; &nbsp; @Autowired val serviceAccaunt: ServiceAccaunt? = null&nbsp; &nbsp; override fun initialize(annotation: UniqueLogin?) {}&nbsp; &nbsp; override fun isValid(login: String, ctx: ConstraintValidatorContext): Boolean {&nbsp; &nbsp; &nbsp; &nbsp; return if (serviceAccaunt!= null) !(serviceAccaunt.isHaveLogin(login)) else true&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答