我在使用验证 @RequestBody 的项目上遇到问题
implementation("org.springframework.boot:spring-boot-starter-validation")
Run Code Online (Sandbox Code Playgroud)
我的 DTO 如下所示:
import javax.validation.constraints.Email
import javax.validation.constraints.Pattern
class LoginDto(
@Email
val email: String,
@Pattern(regexp = Constants.PASSWORD_REGEX)
val password: String
)
Run Code Online (Sandbox Code Playgroud)
控制器看起来像这样:
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
import javax.validation.Valid
@RestController
@Validated
class AuthController(private val authService: AuthService) {
@PostMapping("login")
fun login(@Valid @RequestBody loginDto: LoginDto): LoginResponse {
return authService.login(loginDto)
}
...
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试传递无效数据,验证不会出现错误:
{
"password":"hello",
"email":"dfdfdfdf"
}
Run Code Online (Sandbox Code Playgroud)
我没有收到错误,我使用 Exposed 而不是 jpa,但我认为这与问题无关