首页 > 编程语言 >javax.validation包校验嵌套属性(List对象)的写法

javax.validation包校验嵌套属性(List对象)的写法

时间:2024-08-06 11:18:36浏览次数:9  
标签:String errorMsg class List private javax value validation public

1 maven依赖

        <!-- Hibernate Validator 用于数据验证 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

2 controller 请求实体

@Slf4j
@Validated
public class TestController {

    @PostMapping(value = "/v1/chat/completions")
    public Flux<AgentChatVo> chat(@Valid @RequestBody AgentChatRequest request) {
        return agentServiceService.chat(request);
    }
}

@Data
public class AgentChatRequest {
    @Schema(description = "")
    private String model;

    @Schema(description = "是否开启stream模式")
    private Boolean stream = false;

    @NotEmpty(message = "The messages cannot be null.")
    @Valid
    private List<Message> messages;

    @ApiModelProperty(hidden = true, value = "aigc 是否使用 ")
    @JsonInclude(value = JsonInclude.Include.NON_NULL)
    private Boolean context = false;

    @Schema(description = "最大长度")
    @JsonProperty(value = "max_tokens")
    @JsonInclude(value = JsonInclude.Include.NON_NULL)
    private String maxTokens;
}

@Data
public class Message {
    @Schema(description = "角色")
    @ApiModelProperty(hidden = true)
    private String role;

    @Schema(description = "问题内容")
    @NotBlank(message = "The content cannot be blank.")
    private String content;

    public void initRole() {
        if (StringUtils.isBlank(this.role)) {
            this.role = AiChatRoleEnum.USER.getCode();
        }
    }
}

3 GlobalExceptionHandler

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler implements ResponseBodyAdvice, RequestBodyAdvice {
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseEntity<Result<Void>> errHandler(MethodArgumentNotValidException exception) {
        log.error("MethodArgumentNotValidException e:", exception);
        String errorMsg = paramException(exception.getBindingResult());
        return ResponseEntity.status(HttpStatus.OK).body(Result.fail(ResultCodeEnum.PARAM_ILLEGAL.code(), errorMsg));
    }

    private String paramException(BindingResult bindingResult) {
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        StringBuilder errorMsg = new StringBuilder();
        for (FieldError fieldError : fieldErrors) {
            String defaultMessage = fieldError.getDefaultMessage();
            if (StringUtils.isNotBlank(defaultMessage)) {
                errorMsg.append(
                    String.format("%s的 %s 字段异常: %s;",  "入参实体", fieldError.getField(), defaultMessage));
            } else {
                errorMsg.append(
                    String.format("%s的%s字段不能被赋值为%s;",  "入参实体", fieldError.getField(),
                        fieldError.getRejectedValue()));
            }
        }
        return errorMsg.toString();
    }
}

4 测试


标签:String,errorMsg,class,List,private,javax,value,validation,public
From: https://www.cnblogs.com/linzm14/p/18344769

相关文章

  • List,Set,Queue,Map接口
    List,Set,Queue,Map接口一.List接口List接口是Java集合框架中的一个重要接口,它继承自Collection接口。List接口表示一个有序的集合,其中的元素可以重复。这意味着在List中,每个元素都有一个特定的索引位置,我们可以通过这个索引来访问或操作元素。List接口的主要特点包括......
  • Androidstudio开发,ListView实现通讯录联系人列表( 四)
    文章目录1.涉及到的技术点2.发环境3.需求分析4.实现步骤5.代码实现全部过程6.效果图7.其它资料学习1.涉及到的技术点数据库SQLite的使用列表控件ListView的使用ListView事件监听适配器BaseAdapter的使用线性布局LinearLayoutCompat的使用2.发环境开发工具......
  • 【日常开发】一个list集合 根据a字段 b字段进行分组 并计算c字段的和 并封装这种格式:
    ......
  • 群辉NAS利用AList搭建混合云盘⑥挂接腾讯微云
    目录……接前文5、挂接腾讯微云未完待续…………接前文5、挂接腾讯微云登录AList后台→管理→存储→驱动供选择“腾讯微云”→填写挂接路径打开“配置文档”(详见前文)打开配置文档→简体中文→开始→找到腾讯微云部分,可以看到关于Cookie的设置方法。手工用浏览器登......
  • 速卖通、美客多自养号经验分享:满足测评条件与Listing优化秘诀
    Listing,即产品在电商平台上的展示页面,是吸引顾客、促进销售的关键窗口。为了在众多竞品中脱颖而出,卖家需精心优化Listing的每一个细节,从类别选择到描述撰写,每一步都至关重要。以下是Listing优化的五大核心策略:1. 类别精准定位分类精准:正确选择产品所属的分类,甚至可考虑添加......
  • LeetCode | 141 linked list cycle
    https://github.com/dolphinmind/datastructure/tree/datastructure-linkedlist分析证明过程基本假设假设环的长度为(C)假设从链表的头部到环的入口点的距离为(A)假设从环的入口点到快慢指针第一次相遇点的距离为(B)假设从快慢指针第一次相遇点回到环的入口点的距离为(C......
  • 易优CMS模板标签uiarclist文档列表
    【基础用法】标签:uiarclist描述:文档列表编辑,比uitext、uihtml、uiupload标签多了一个typeid属性,使用时结合html一起才能完成可视化布局,只针对具有可视化功能的模板。用法:<divclass="eyou-edit"e-id="文件模板里唯一的数字ID"e-page='文件模板名'e-type="arclist">{eyou:uiar......
  • 在Python中,list1[::] = list2的空间复杂度是多少?
    此代码首先迭代列表nums,更新整数0、1、2(也分别称为红色、白色和蓝色)的计数。nums保证只有整数0、1和/或2。找到计数后,代码使用[::],这是一种就地修改列表的技巧,以排序numsdefsortColors(self,nums:List[int])->None:re......
  • Python 基础教程:List(列表)的使用
    《Python基础教程:List(列表)的使用》在Python中,列表是最基本的数据结构之一,它是一种有序的、可变的数据集合,可以包含任意类型的元素,包括数字、字符串、其他列表等。1.列表的创建列表使用方括号[]创建,列表中的元素用逗号,分隔。#创建一个包含整数的列表numbers......
  • LeetCode | 160 Intersection of two linkedlists
    https://github.com/dolphinmind/datastructure/tree/datastructure-linkedlist分析判断两个链表是否相交,转换成了双指针相遇的问题。还是那句话,双指针的本质是遍历,走的路其实一样/***解决两个链接不相交而陷入无限循环的情况*初......