Java-Post传参参数校验
前言
本文主要介绍在post方式下,利用@Valid和@Validated校验参数的方式。
格式校验
代码如下:
package com.yeso.manager.controller;
import com.yeso.manager.common.Result;
import com.yeso.manager.domain.dto.DemoDTO;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
/**
* @Author lp
* @Date 2023/12/5
*/
@RequestMapping("/demo")
@RestController
public class Demo {
@PostMapping("/checkData")
public Result checkData(@RequestBody @Valid DemoDTO demoDTO) {
return Result.success("数据格式校验成功!");
}
}
package com.yeso.manager.domain.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.Valid;
import javax.validation.constraints.*;
import java.util.List;
/**
* @Author lp
* @Date 2023/12/5
*/
@Data
@ApiModel("demo(DTO)")
public class DemoDTO {
@ApiModelProperty(name = "年龄",required = true)
@NotNull(message = "年龄不能为空")
@Min(value = 1,message = "年龄最小为1")
@Max(value = 130,message = "年龄最大为130")
private Integer age;
@ApiModelProperty(name = "姓名",required = true)
@NotBlank(message = "姓名不能为空")
@Length(min = 1,max = 10,message = "名称长度在1-10之间")
private String name;
@ApiModelProperty(name = "手机",required = true)
@NotBlank(message = "手机不能为空")
@Pattern(regexp = "^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\\d{8}$",message = "手机格式错误")
private String phone;
@ApiModelProperty(name = "邮箱",required = true)
@NotBlank(message = "邮箱不能为空")
@Email(regexp = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$",message = "邮箱格式错误")
private String email;
@ApiModelProperty(name = "邮箱1",required = true)
@NotBlank(message = "邮箱1不能为空")
@Pattern(regexp = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$",message = "邮箱1格式错误")
private String email1;
@ApiModelProperty(name = "爱好集合",required = true)
@NotEmpty(message = "爱好集合不能为空")
private List<String> hobby;
@ApiModelProperty(name = "爱好集合",required = true)
@NotEmpty(message = "爱好集合不能为空")
@Valid
private List<BookDTO> books;
}
package com.yeso.manager.domain.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.*;
import java.math.BigDecimal;
import java.util.List;
/**
* @Author lp
* @Date 2023/12/5
*/
@Data
public class BookDTO {
@ApiModelProperty(name = "书名",required = true)
@NotBlank(message = "书名不能为空")
@Length(min = 1,max = 10,message = "名书名长度在1-10之间")
private String bookName;
@ApiModelProperty(name = "价格",required = true)
@NotNull(message = "价格不能为空")
@DecimalMin(value = "0.1",message = "价格最低为0.1")
@DecimalMax(value = "100",message = "价格最高为100")
private BigDecimal bookPrice;
@ApiModelProperty(name = "版本",required = true)
@NotEmpty(message = "版本集合不能为空")
private List<Integer> bookVersion;
}
测试结果: