首页 > 解决方案 > Kotlin 中的 Spring RequestParam 验证不起作用

问题描述

我正在尝试@RequestParam在 Kotlin 中进行验证,但它不起作用。目前我正在使用 Kotlin 1.4.20、Spring boot 2.3.5 和 java 1.8。

这是我的控制器:

@Validated
@RestController
@RequestMapping("api/v1/")
class myController{

    @GetMapping("/age", produces = [MediaType.APPLICATION_JSON_VALUE])
    fun findArticlesByAge(@RequestParam @Valid @Min(6) age: Int): ResponseEntity<Article> =
            ResponseEntity
                .ok()
                .body(Article())
}

Hibernate 验证器已经在有效的 pom 中:

      <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.1.6.Final</version>
      </dependency>

要求:

http://localhost:8080/api/v1/age?age=2

回复:

200

这是不起作用的简单验证,但是我想通过自定义注释和ConstraintValidator. 如果我让它在简单的情况下工作,@Min(6)它可能也会开始使用自定义注释。

标签: spring-bootkotlin

解决方案


所以缺少一个依赖项:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

我添加了这个,验证开始工作。但是,它会在验证消息中引发 500 内部服务器错误,这可以通过ControllerAdvice.


推荐阅读