spring boot中接收页面传过来的参收将其映射到实体中并进行校验;
用到的注解会有:
@Null 被注释的元素必须为null
@NotNull 备注是的元素不能null 必须要传 可以为空值
@AssertTrue 被注释的元素必须为true
@AssertFalse 被注释的元素必须是false
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max,min) 被注释的元素的大小必须在指定的范围内
@Digits(integer,fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past 被注释的元素必须是一个过去的日期
@Future 被注释的元素必须是一个将来的日期
@Pattern(value) 被注释的元素必须符合指定的正则表达式
@Email 被注释的元素必须是电子邮箱地址
@Length 备注是的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串必须非空 必须要传 值不可以为空(只是长度) 可以为一个连续空格的字符串 例如:" "是可以的;
@Range 被注释的元素必须在合理的范围内
@NotBlank 必须要传 会先将空格去掉然后判断是否为空的字符串 例如:" "是不行的;
```html
在这里插入代码片
代码中进行引用
首先创建一个接收参数的实体类
@Data
@EqualsAndHashCode(callSuper = false)
@ApiModel(value = "request参数接收对象", description = "request参数接收对象")
public class DataVo implements Serializable {
private static final long serialVersionUID = 1L;
@NotNull(message = "用户ID必须要传")
@ApiModelProperty(value = "id唯一标识", required = true)
private String id;
@Null(message = "姓名不可以传,必须为空")
@ApiModelProperty(value = "姓名", required = true)
private String name;
@NotEmpty
@ApiModelProperty(value = "这是一个集合")
private List<String> list;
@Min(10)
@ApiModelProperty(value = "年龄", required = true)
private Integer age;
@DecimalMin("1.0")
@NotNull
@Max(12)
@ApiModelProperty(value = "年月", required = true)
private Integer yearMonth;
@NotBlank
@ApiModelProperty(value = "性别")
private String sex;
@ApiModelProperty(value = "邮箱", required = true)
private String email;
}
在controller中利用注解进行参数映射
@ApiOperation(value = "新增加一条数据")
@PostMapping("/adddata")
public Dto addData(@RequestBody @Valid DataVo dataVo){
System.out.println(dataVo);
return DtoUtil.returnSuccess("成功",dataVo);
}```
```html
在这里插入代码片
- 在controller中首先利用@RequestBody将页面传递过来的参数进行映射到实体中去;此时只是做了映射,并没有进行校验;
- 在实体中利用注解进行校验,在controller中用@Valid开启校验,此时参数的校验才会生效;
注:swagger中的@required注解跟spring boot的@required的并不一样;
当swagger中的@required为true时,参数为空依然可以进行访问;
当springboot中的@required为true时,参数为空会进行拦截;
所以说swagger中的@required只是为了在api页面中进行显示,告诉看文档的人这个参数应该如何传,并没有真正的拦截;