Kotlin Spring Boot验证不起作用。

huangapple go评论99阅读模式
英文:

Kotlin spring boot validation does not work

问题

When making a POST request to /register with a user containing a null email, you expect it to display a message like "hey, you have null in the email field." However, it throws a NullPointerException during the saving step because of the user.email!! statement. When sending JSON with an incorrect email format, it passes through the @Email constraint annotation, and validation doesn't work.

Controller class:

@RestController
class UserController(
        @Autowired val userService: UserService) {

    @PostMapping(
            path=["/register"],
            consumes=["application/json"],
            produces=["application/json"])
    fun registerNewUser(
            @Valid @RequestBody user: User): UserDTO {
        user.encryptPassword()
        userService.registerNewUser(user)
        return UserDTO(user)
    }
}

User class:

@Entity
class User(
        @get:NotNull @field:ValidEmail @Column(unique = true)
        var email: String? = null,
        @get:NotNull @Column(unique = true)
        var username: String? = null,
        @get:NotNull @field:ValidPhoneNumber @Column(unique = true)
        var phoneNumber: String? = null,
        @get:NotNull @field:ValidPassword
        var password: String? = null,
        @get:NotNull
        var role: Role? = null,

        var address: String? = null
) : BaseEntity() {
    fun encryptPassword() {
        password = BCryptPasswordEncoder().encode(password)
    }
}

@MappedSuperclass
open class BaseEntity(
        @Id @NotNull @GeneratedValue(generator = "UUID")
        @GenericGenerator(name="UUID", strategy = "org.hibernate.id.UUIDGenerator")
        open val id: UUID? = null)

It seems like you've tried various approaches to make the validation work, including different annotations, but encountered issues. It's challenging to diagnose the problem without more context or error messages. If you have specific questions or issues you'd like to address, please provide more details, and I'll try to assist you further.

英文:

When i do a POST request to /register with user with null email, i expect it to say something "hey, you have null in email field", but it throws NPE on saving step because of user.email!! statement.
When i send json with wrong email like this:

{
  "email": "wrongEmailAddress",
  "username": "username",
  "phoneNumber": "+7 909 909 9009",
  "password": "234adfg24",
  "role": "USER"
}

it perfectly passes through this constraint annotation:

@Email
@Pattern(regexp = ".+@.+\\..+", message = "Please provide a valid email address")
@Target(
        AnnotationTarget.FIELD,
        AnnotationTarget.FUNCTION,
        AnnotationTarget.ANNOTATION_CLASS,
        AnnotationTarget.PROPERTY,
        AnnotationTarget.PROPERTY_GETTER)
@Retention(AnnotationRetention.RUNTIME)
@Constraint(validatedBy = [])
@MustBeDocumented
annotation class ValidEmail(
        val message: String = "Please provide a valid email address",
        val groups: Array<KClass<out Any>> = [],
        val payload: Array<KClass<out Payload>> = []
)

request screenshot

Why does not validation work?

Controller class:

@RestController
class UserController(
        @Autowired val userService: UserService) {

    @PostMapping(
            path=["/register"],
            consumes=["application/json"],
            produces=["application/json"])
    fun registerNewUser(
            @Valid @RequestBody user: User): UserDTO {
        user.encryptPassword()
        userService.registerNewUser(user)
        return UserDTO(user)
    }
}

User class:

@Entity
class User(
        @get:NotNull @field:ValidEmail @Column(unique = true)
        var email: String? = null,
        @get:NotNull @Column(unique = true)
        var username: String? = null,
        @get:NotNull @field:ValidPhoneNumber @Column(unique = true)
        var phoneNumber: String? = null,
        @get:NotNull @field:ValidPassword
        var password: String? = null,
        @get:NotNull
        var role: Role? = null,

        var address: String? = null
) : BaseEntity()
{
    fun encryptPassword() {
        password = BCryptPasswordEncoder().encode(password)
    }
}

@MappedSuperclass
open class BaseEntity(
        @Id @NotNull @GeneratedValue(generator = "UUID")
        @GenericGenerator(name="UUID", strategy = "org.hibernate.id.UUIDGenerator")
        open val id: UUID? = null)

What i tried. I tried to change between @ValidEmail, @get:ValidEmail, @field:ValidEmail ( https://stackoverflow.com/questions/35847763/kotlin-data-class-bean-validation-jsr-303 , https://stackoverrun.com/ru/q/9883168 and other sources), tried to rewrite everything in java. Nothing works. PhoneNumberValidator passes all unit tests, but the constraint @ValidPhoneNumber does not work too. Not even one constraint work.
Thanks for any suggestions.

答案1

得分: 4

标记你的RestController为@Validated。

英文:

Mark your restcontroller with @Validated.

huangapple
  • 本文由 发表于 2020年8月2日 21:26:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63216544.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定