|
|
|
# 业务参数校验
|
|
|
|
|
|
|
|
业务参数校验采用JSR-303方式,关于JSR-303介绍可以参考这篇博文:[JSR 303 - Bean Validation 介绍及最佳实践](https://www.ibm.com/developerworks/cn/java/j-lo-jsr303/)
|
|
|
|
|
|
|
|
在参数中使用注解即可,框架会自动进行验证。如下面一个添加商品接口,它的参数是GoodsParam
|
|
|
|
|
|
|
|
```java
|
|
|
|
@ApiMapping(value = "goods.add")
|
|
|
|
public void addGoods(GoodsParam param) {
|
|
|
|
...
|
|
|
|
}
|
|
|
|
```
|
|
|
|
在GoodsParam中添加JSR-303注解:
|
|
|
|
|
|
|
|
```java
|
|
|
|
@Data
|
|
|
|
public class GoodsParam {
|
|
|
|
@NotEmpty(message = "商品名称不能为空")
|
|
|
|
private String goods_name;
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
如果不传商品名称则返回
|
|
|
|
|
|
|
|
```
|
|
|
|
{"goods_add_response":{"msg":"Success","code":"10000","sub_msg":"商品名称不能为空","sub_code":"isv.invalid-parameter"},"sign":"Eh3Z5CxDCHsb4MyYFVxsPSmBpwVi1LISJdOkrzglxXoqG7RVyEOt4ef1kNpznUvMI3FDQU1suR7Rsmx6NjGdEVS6NSH2Kt0d8TFBRpLhWz8hApnxOtgzqMqbYeMuJie7X5gF6m8hTnvuuxF21IrkixMe+lyBcXw7dk0C3w1SwdEZkHQ+xC+M4bLqAZt5/3kl79/FWSMFJWHiZmg5YeEi8e8XhYCNcz+xlJRJL0x2Y87fFxqSY0UYWNxbQHgdVI8xRfn1n31nzkcLxiAtTh4LPtNRrG7w7absK/C1Oi/vczuBlFeq2EWUsYVWOVpKiJifUwvYVUUsztSLElzplzOjbg=="}
|
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
- 校验顺序
|
|
|
|
|
|
|
|
如果存在多个注解,可以指定groups来控制校验顺序,如下代码所示:
|
|
|
|
|
|
|
|
```java
|
|
|
|
@NotBlank(message = "NotBlank", groups = Group1.class)
|
|
|
|
// 优先校验Group2
|
|
|
|
// 可交换下面Group2,Group3,看下校验顺序
|
|
|
|
@Length(min = 2, max = 20, message = "length must 10~20", groups = Group2.class)
|
|
|
|
@Pattern(regexp = "[a-zA-Z]*", message = "name must letters", groups = Group3.class)
|
|
|
|
private String name;
|
|
|
|
```
|
|
|
|
|
|
|
|
优先校验`@Length`,通过后再校验`@Pattern`
|
|
|
|
|
|
|
|
## 参数校验国际化
|
|
|
|
|
|
|
|
国际化的配置方式如下:
|
|
|
|
|
|
|
|
```java
|
|
|
|
@NotEmpty(message = "{goods.remark.notNull}")
|
|
|
|
private String goods_remark;
|
|
|
|
```
|
|
|
|
|
|
|
|
国际化资源文件`bizerror_en.properties`中添加:
|
|
|
|
```
|
|
|
|
goods.remark.notNull=The goods_remark can not be null
|
|
|
|
```
|
|
|
|
|
|
|
|
bizerror_zh_CN.properties中添加:
|
|
|
|
|
|
|
|
```
|
|
|
|
# 商品备注不能为空
|
|
|
|
goods.remark.notNull=\u5546\u54c1\u5907\u6ce8\u4e0d\u80fd\u4e3a\u7a7a
|
|
|
|
```
|
|
|
|
|
|
|
|
## 参数校验国际化传参
|
|
|
|
|
|
|
|
下面校验商品评论的长度,要求大于等于3且小于等于20。数字3和20要填充到国际化资源中去。
|
|
|
|
|
|
|
|
```
|
|
|
|
// 传参的格式:{xxx}=value1,value2...
|
|
|
|
@Length(min = 3, max = 20, message = "{goods.comment.length}=3,20")
|
|
|
|
private String goods_comment;
|
|
|
|
```
|
|
|
|
|
|
|
|
bizerror_en.properties:
|
|
|
|
```
|
|
|
|
goods.comment.length=The goods_comment length must >= {0} and <= {1}
|
|
|
|
```
|
|
|
|
|
|
|
|
bizerror_zh_CN.properties中添加:
|
|
|
|
|
|
|
|
```
|
|
|
|
# 商品评论长度必须在{0}和{1}之间
|
|
|
|
goods.comment.length=\u5546\u54c1\u8bc4\u8bba\u957f\u5ea6\u5fc5\u987b\u5728{0}\u548c{1}\u4e4b\u95f4
|
|
|
|
```
|
|
|
|
这样value1,value2会分别填充到{0},{1}中
|