控制器方法中requestBody上的Spring Boot @Valid无法正常工作 [英] Spring boot @Valid on requestBody in controller method not working

查看:415
本文介绍了控制器方法中requestBody上的Spring Boot @Valid无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证由@Validated注释的@RestController中由@Valid注释注释的简单请求正文.验证对请求中的原始变量正确起作用(在下面的示例中,对年龄有效),但对pojo请求正文不起作用.@Valid注释对请求正文Person类(即控制器接受18岁以下的空白名称和年龄)无效.

I am trying to validate a simple request body annotated by @Valid annotation in a @RestController annotated by @Validated. Validations are working correctly on primitive variable in request (on age in below example) but not working on pojo request body. @Valid annotation has no effect on request body Person class (i.e. controller accepting blank name and age under 18).

人员班级:

import javax.validation.constraints.Min
import javax.validation.constraints.NotBlank

class Person (

    @NotBlank
    val name : String,

    @Min(18)
    val age : Int
)

控制器类:

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 HomeController {

    @GetMapping("/{age}")
    fun verifyAge(@PathVariable("age") @Min(18) age:Int): String {
        return "Eligible age."
    }

    @PostMapping
    fun personValidation(@Valid @RequestBody person : Person) : String {
        return "No validation error"
    }
}

@ NotBlank,@ Min和@Valid注释来自以下依赖项:

@NotBlank, @Min and @Valid annotations came from below dependency:

    implementation("org.springframework.boot:spring-boot-starter-validation:2.3.0.RELEASE")

如何使@Valid在@Validated控制器中的Person请求主体上工作?

How to make @Valid working on Person request body in a @Validated controller?

推荐答案

这也对我有用(在构造函数参数上添加字段注释),得到了一位用户的回答:

This also worked for me (adding field annotation on constructor arguments) as answered by one of the user:

import javax.validation.constraints.Min
import javax.validation.constraints.NotBlank

class Person (

    @field:NotBlank
    val name : String,

    @field:Min(18)
    val age : Int
)

尽管更改了"kotlin",如下所示对Person的类定义(无参数的构造函数参数)(在大括号{...}后面加上括号(...))也可以在不使用@field注释的情况下使用:

Though changing the "kotlin" class definition of Person as below (constructor arguments to no-arguments) (note parentheses (...) to curly-brackets{...}) also worked without putting @field annotaion:

import javax.validation.constraints.Min
import javax.validation.constraints.NotBlank

class Person {

    @NotBlank
    lateinit var name: String

    @Min(18)
    var age: Int = 0
}

这篇关于控制器方法中requestBody上的Spring Boot @Valid无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆