【问题标题】:Kotlin and Spring Boot Request Body ValidationKotlin 和 Spring Boot 请求正文验证
【发布时间】:2018-08-08 23:34:49
【问题描述】:

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

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

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

和一个控制器

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

好吧,使用任何请求正文发出请求只会引发 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 = ""

或者也许:

name: String? = null

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

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

在此示例中,只有一个参数,但手动处理较大的类似乎不是一个好方法

提前致谢

【问题讨论】:

标签: spring validation spring-boot kotlin httprequest


【解决方案1】:

我认为以下由两部分组成的解决方案可能适用于Spring Boot 2.x:


API 外观配置

@Configuration
class ValidationRouter(
        val validationService: ValidationService
) {

    @Bean
    fun router() = router {
        accept(APPLICATION_JSON).nest {
            "/api".nest {
                POST("/validation") { req ->
                    req.bodyToMono(ValidatingBody::class.java)
                            .doOnNext(validationService::validate)
                            .flatMap { ServerResponse.ok().build() }
                            .onErrorResume(BodyValidationException::class.java, validationService::handle)
                }
            }

        }

    }

    data class ValidatingBody(
            @get:NotBlank(message = "should not be blank")
            var mandatoryText: String?,
            @get:Size(min = 2, max = 10, message = "should contain more than 2 and less than 10 characters")
            @get:NotBlank(message = "should not be blank")
            var sizedText: String?,
            @get:Min(value = 1, message = "should be no less than 1")
            @get:Max(value = 10, message = "should be no greater than 10")
            @get:NotNull(message = "should be specified")
            var limitedNumber: Int?
    )
}

验证机制

@Service
class ValidationService(val validator: Validator) {

    private val log = LoggerFactory.getLogger(ValidationService::class.java)

    @Throws(BodyValidationException::class)
    fun <T> validate(o: T) {
        val violations = validator.validate(o)
        if (violations.isEmpty()) return

        throw BodyValidationException.of(violations.stream()
                .map { v: ConstraintViolation<T> -> "${v.propertyPath} ${v.message}" }
                .collect(Collectors.toSet()).toMutableSet())
    }

    fun handle(e: BodyValidationException): Mono<ServerResponse> =
            handleInternal(ErrorResponse(e.errors))

    private fun handleInternal(response: ErrorResponse): Mono<ServerResponse> =
            Mono.just(response)
                    .doOnNext { res -> log.warn(res.errors.joinToString(",")) }
                    .flatMap { res ->
                        badRequest().contentType(APPLICATION_JSON)
                                .bodyValue(res)
                    }

    data class ErrorResponse(val errors: Set<String>)

    class BodyValidationException private constructor(var errors: Set<String>) : IllegalArgumentException() {
        companion object {
            fun of(errors: Set<String>): BodyValidationException {
                return BodyValidationException(errors)
            }
        }

    }
}

【讨论】:

    【解决方案2】:

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

    JSON Schema 就是其中之一,并且有几种实现方式。 Spring Data Rest 包含它,所以这可能是您的首选,因为 Spring Boot 将它包装得很好。

    【讨论】:

      猜你喜欢
      • 2020-10-18
      • 2020-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-11
      • 2018-12-05
      相关资源
      最近更新 更多