Kotlin 和 Spring Boot 请求正文验证

Mig*_*ães 5 validation spring httprequest kotlin spring-boot

我刚刚开始使用 kotlin 和 Spring Boot 来开发一个简单的 Web 应用程序。

让我们来看一个简单的数据类对象

@Entity  
data class User (name: String) {  
  @Id @GeneratedValue(strategy = GenerationType.AUTO)  
  var id: Long = -1  
}  
Run Code Online (Sandbox Code Playgroud)

和一个控制器

@RequestMapping(method = arrayOf(RequestMethod.POST))
fun createUser (@RequestBody user: User): User {
    return userService.createUser(user)
}
Run Code Online (Sandbox Code Playgroud)

好吧,使用任何请求正文发出请求只会引发 http 400 错误 no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?); nested exception is com.fasterxml.jackson.databind.JsonMappingException

为了消除这个错误,我发现我们需要为构造函数参数提供一些默认值,因此:

name: String = ""
Run Code Online (Sandbox Code Playgroud)

或者可能:

name: String? = null
Run Code Online (Sandbox Code Playgroud)

现在,响应正文中的输入绝对没有验证,这意味着,如果其中存在的 JSON 不遵守 User 类的语法,则将使用默认值并将其存储在数据库中。

是否有任何方法可以验证请求正文 JSON 输入以抛出错误请求(如果它不符合 User 类参数而无需手动执行)?

在这个例子中只有一个参数,但手动使用更大的类似乎不是一个好方法

提前致谢

Pau*_*cks 0

是的,有一些方法可以“自动”验证请求正文 JSON。

JSON Schema就是其中之一,并且有多种实现。Spring Data Rest包含它,所以这可能是您的第一选择,因为 Spring Boot 很好地包装了它。