繁体   English   中英

springboot,如何有效@RequestBody

[英]springboot, how to valid @RequestBody

当前代码

    @Slf4j
    @RestController
    public class TestController {
        @Validated
        @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
        String test( @RequestBody @NotEmpty @Valid List<@NotBlank @Valid UUID> uuids) {
            return uuids.toString();
        }
    }

问题

--header 'Content-Type: application/json' \
--data-raw '[]'

curl --location --request PUT 'localhost:8080' \
--header 'Content-Type: application/json' \
--data-raw '[""]'

有效通行证。 但我不想要

我想验证上面示例中的 curl 请求。 没有dto有什么办法吗?

正确的做法

@Slf4j
@RestController
@Validated
public class TestController {
    @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
    String test( @RequestBody @NotEmpty @Valid List<@NotNull @Valid UUID> 
     uuids) {
        return uuids.toString();
    }
}

我们必须用@Validated 注释要验证的bean。 对于 UUID,@NotNull 也可以满足要求,因为 object UUID 的此约束不存在验证器

验证消息也可以通过为@NotEmpty 和@NotNull 提供“消息”参数来定制。 比如@NotEmpty(message = "不能为空")

如果任何验证失败,则会引发 ConstraintViolationException。 可以做异常处理来自定义这个异常并抛出 400 Bad Request。

在字段上添加评论

@Getter
@Setter
public class Person {
    @NotNull(message = "[id] cannot be empty")
    private Long id;

    @NotBlank(message = "[name] cannot be blank")
    private String name;
    @NotBlank(message = "[email] cannot be blank")
    private String email;
    @NotBlank(message = "[birthday] cannot be blank")
    private Date birthday;

    @Override
    public String toString() {
        return JSONUtils.toJSONString(this);
    }
}

使用@Validated进行验证

@RestController
@RequestMapping
public class TestController {

    @PostMapping(value = "/get")
    public String get(@Validated @RequestBody Person person) {
        return person.toString();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM