【问题标题】:Spring RequestParam validation in Kotlin is not workingKotlin 中的 Spring RequestParam 验证不起作用
【发布时间】:2021-03-14 19:33:18
【问题描述】:

我正在尝试在 Kotlin 中验证 @RequestParam,但它不起作用。目前我正在使用 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-boot kotlin


    【解决方案1】:

    所以缺少一个依赖项:

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

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

    【讨论】:

      猜你喜欢
      • 2020-11-22
      • 2020-11-15
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多