文章目录
前言
以下案例代码全部基于spring boot
集成
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
<version>2.9.2</version>
</dependency>
一、swagger使用
1.controller、方法注解
@Api(tags = "注解分组")
public class controller {
@ApiOperation(value = "接口名称",notes = "接口说明")
public String selectAll(Query query) {
return "";
}
@ApiOperation(value = "接口名称",notes = "接口说明")
@ApiImplicitParams(
@ApiImplicitParam(name="参数说明",value = "参数名称",required = true,example = "参数值")
)
public String selectOne(Long id) {
return "";
}
}
2.bean参数注解
@ApiModel(value = "类名", description = "类说明")
public class 类名 {
@ApiModelProperty(value = "变量说明",example = "参数例值",required = true,hidden = true)
private int id;
}
@ApiParam()
用途:
用于方法,参数,字段说明;表示对参数的添加元数据(说明或是否必填等)
参数:
- name–参数名
- value–参数说明
- required–是否必填
@ApiModelProperty
用途:
用于修饰参数类中的变量
参数:
- value–字段说明
- name–重写属性名字
- dataType–重写属性类型
- required–是否必填
- example–举例说明
- hidden–隐藏
- allowableValues-可选参数
二、Valid接口验证
1.bean类注解
public class 类名 {
@NotNull(message = "参数为null,错误提示")
@Range(min=0,max=1,message = "参数范围错误提示")
private int id;
@Size(max = 30, message = "参数长度错误提示")
private String title;
}
2.controller注解
public class controller {
public String selectAll( @Valid @RequestBody Query query) {
return "";
}
}
3.注解详细解释
空检查
@Null 验证对象是否为null
@NotNull 验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty 检查约束元素是否为NULL或者是EMPTY.
Booelan检查
@AssertTrue 验证 Boolean 对象是否为 true
@AssertFalse 验证 Boolean 对象是否为 false
长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内
@Length(min=, max=) Validates that the annotated string is between min and max included.
日期检查
@Past 验证 Date 和 Calendar 对象是否在当前时间之前
@Future 验证 Date 和 Calendar 对象是否在当前时间之后
@Pattern 验证 String 对象是否符合正则表达式的规则
数值检查,建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单值为“”时无法转换为int,但可以转换为Stirng为"",Integer为null
@Min 验证 Number 和 String 对象是否大等于指定的值
@Max 验证 Number 和 String 对象是否小等于指定的值
@DecimalMax 被标注的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度
@DecimalMin 被标注的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度
@Digits 验证 Number 和 String 的构成是否合法
@Digits(integer=,fraction=) 验证字符串是否是符合指定格式的数字,interger指定整数精度,fraction指定小数精度。
@Range(min=, max=) Checks whether the annotated value lies between (inclusive) the specified minimum and maximum.
@Range(min=10000,max=50000,message=“range.bean.wage”)
private BigDecimal wage;
@CreditCardNumber信用卡验证
@Email 验证是否是邮件地址,如果为null,不进行验证,算通过验证。
@ScriptAssert(lang= ,script=, alias=)
@URL(protocol=,host=, port=,regexp=, flags=)