Hello,
I want to ask some question about validating input in Spring.
I have this class for input data:
class Post(
@NotNull
val content: String?,
@NotNull
val id: Int?
)
and I have this class for validating:
@RestController
class PostController {
@PostMapping("/create")
fun createPost(@Validated @RequestBody post: Post): String {
println(post.content.length) // This should not compile error because @NotNull and @Validated
return "Success"
}
}
That should not compile error because @NotNull and @Validated (like smart cast). It can be solved with something like this:
println(post.content!!.length)
But that code will not so good with !! operation.
Or it can be solved with non-null type in Post (but with difference type of error). This solution will not work if I have this class for validating:
@RestController
class PostController2 {
@PostMapping("/create2")
fun createPost2(@Validated @RequestBody post: Post, bindingResult: BindingResult): String {
if (bindingResult.hasErrors()) {
// post.content is nullable
return "Error"
} else {
// post.content is non-null
println(post.content.length)
return "Success"
}
}
}
Is there any good solution for this problem?
Thank you.