【问题标题】:How to validate unwanted request body parameters for POST method in Rest API in Spring Boot如何在 Spring Boot 的 Rest API 中验证 POST 方法的不需要的请求主体参数
【发布时间】:2020-11-10 00:37:21
【问题描述】:

请求正文包含如下数据 { “姓名”:“嗨”, “年龄”:10, “你好”:”” }

但在 Rest Controller 中,我试图在 DTO、RestControllerDTO.class 的帮助下获取这些数据

公共 RestControllerDTO {

@Notblank 私有字符串名称;

@Notblank 私人整数年龄;

// getter 和 setter

}

现在我想在进入控制器类之前抛出一个异常,因为“hi”是一个未知字段。

【问题讨论】:

  • 你能详细说明你想要做什么吗?
  • 如果您使用jackson进行json反序列化,请尝试在application.properties中设置spring.jackson.deserialization.fail-on-unknown-properties=truesource

标签: spring validation


【解决方案1】:

您可以通过在控制器方法中使用 @Valid 注释来做到这一点

@GetMapping("/foo")
public void bar(@Valid RestControllerDTO dto, BindingResult bindingResult) {

    if (bindingResult.hasErrors()) {
        throw new Exception();
    }
...

https://spring.io/guides/gs/validating-form-input/

我还建议添加@NotNull,因为@NotBlank 只检查“”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 2016-07-13
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 2019-11-06
    相关资源
    最近更新 更多