【问题标题】:Spring Boot - Required @RequestBody class fieldsSpring Boot - 必需的 @RequestBody 类字段
【发布时间】:2020-05-06 07:53:07
【问题描述】:

我有以下 API 定义:

@ResponseBody
@PostMapping(path = "/configureSection")
public ResponseEntity<ResultData> configureSegment(@RequestParam() String Section,
                                                       @RequestBody SectionConfig sectionConfig);
public class SegmentConfig {
    @JsonProperty(value = "txConfig", required = true)
    TelemetryConfig telemetryConfig;
    @JsonProperty(value = "rxConfig")
    ExternalConfig externalConfig;
}

我定义了 txConfig 是必需的属性(即类),但是当发送空 JSON ({}) 时,spring boot 仍然运行 API,而我希望它返回参数 tsConfig 未设置的错误。

知道我错过了什么吗?

编辑:使用@Valid 和@NotNull 解决了它,但返回的错误信息量太大,有什么方法可以解决它?

 {
    "timestamp": 1588753367913,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.bind.MethodArgumentNotValidException",
    "errors": [
        {
            "codes": [
                "NotNull.segmentConfig.telemetryConfig",
                "NotNull.telemetryConfig",
                "NotNull.services.TelemetryConfig",
                "NotNull"
            ],
            "arguments": [
                {
                    "codes": [
                        "segmentConfig.telemetryConfig",
                        "telemetryConfig"
                    ],
                    "arguments": null,
                    "defaultMessage": "telemetryConfig",
                    "code": "telemetryConfig"
                }
            ],
            "defaultMessage": "Please provide a valid txConfig",
            "objectName": "segmentConfig",
            "field": "telemetryConfig",
            "rejectedValue": null,
            "bindingFailure": false,
            "code": "NotNull"
        }
    ],
    "message": "Bad Request",
    "path": "/mypath"
}`

【问题讨论】:

  • 尝试在telemetryConfig 字段上添加@Valid 注释

标签: java spring-boot jackson


【解决方案1】:

使用@Valid 和@NotNull 注解验证如下:-

@ResponseBody
    @PostMapping(path = "/configureSection")
    public ResponseEntity<ResultData> configureSegment(@RequestParam() String Section,
                                                       @RequestBody @Valid SectionConfig sectionConfig
                                                        )  {

public class SegmentConfig {

    @JsonProperty(value="txConfig", required = true)
    @NotNull(message="Please provide a valid txConfig")
    TelemetryConfig telemetryConfig;
    @JsonProperty(value="rxConfig")
    ExternalConfig externalConfig;

}

【讨论】:

  • 谢谢!错误器有点奇怪 - 实际上非常大而且信息量太大 - 有什么办法可以改变它?将代码添加到问题中
  • @TheUnreal 您是否在异常处理程序中处理MethodArgumentNotValidException
  • @Eklavya 没有。也不确定你的意思是我能做什么。有参考吗?
  • @TheUnreal 查看已接受答案的更新部分stackoverflow.com/questions/50737381/…
猜你喜欢
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 2018-06-12
  • 1970-01-01
  • 1970-01-01
  • 2020-12-16
相关资源
最近更新 更多