1. 引入依赖:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.1.0.Final</version>
</dependency>

2. 单个参数校验:

但是单个参数校验会与swagger起冲突,即导致接口文档无法读取到除@GetMapping请求外的参数

@RestController
//必须定义在controller上面
@Validated
public class AdminTagController {
    //单个参数校验
    @RequestMapping("/test")
    public String test(@Size(max= 3) String test){
        return "success";
    }
}

3. 多个参数校验

@Data  
@AllArgsConstructor  
@NoArgsConstructor  
@ApiModel("学生提交作业参数列表")  
public class AddRecordParam {  
  
    /** 节编号*/  
    @ApiModelProperty(value = "节编号",dataType = "Long",required = true)  
    @NotNull(message = "节编号不能为空")  
    private Long sectionId;  
  
    /** 提交文件url地址*/  
    @ApiModelProperty(value = "提交文件url地址",dataType = "String",required = true)  
    @Pattern(message = "url地址不正确",regexp = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]")  
    @NotBlank(message = "提交文件url地址不能为空")  
    private String presentDocumentUrl;  
  
    /** 提交文件名称*/  
    @ApiModelProperty(value = "提交文件名称",dataType = "String",required = true)  
    @NotBlank(message = "提交文件名不能为空")  
    private String documentName;  
  
}
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐