栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Spring Boot中验证JSON请求?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Spring Boot中验证JSON请求?

您可以执行以下操作:说这是请求类:

public class DummyRequest {    @NotNull    private String  pre;    @NotNull    private String  someField;    @NotNull    private String  someOtherField;    @NotNull    private Double  length;    @NotNull    private Double  breadth;    @NotNull    private Double  height;    // getters and setters}

然后,您可以编写自己的通用validate方法,该方法将给出“不太冗长”的约束违反消息,如下所示:

public static <T> List<String> validate (T input) {    List<String> errors = new ArrayList<>();    Set<ConstraintViolation<T>> violations = Validation.buildDefaultValidatorFactory().getValidator().validate(input);    if (violations.size() > 0) {        for (ConstraintViolation<T> violation : violations) { errors.add(violation.getPropertyPath() + " " + violation.getMessage());        }    }    return errors;}

现在,您可以验证并检查您的请求是否包含任何错误。如果是,则可以打印它(或发送回无效的请求消息)。

public static void main (String[] args) {    DummyRequest request = new DummyRequest();    request.setCode("Dummy Value");    List<String> validateMessages = validate(request);    if (validateMessages.size() > 0 ) {        for (String validateMessage: validateMessages) { System.out.println(validateMessage);        }    }}Output:--------height may not be nulllength may not be nullsomeField may not be nullsomeOtherField may not be nullbreadth may not be null


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/370631.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号