Skip to content

Commit 9153628

Browse files
author
yadong.zhang
committed
Springboot使用Validator校验参数
1 parent 64d72e1 commit 9153628

File tree

11 files changed

+485
-1
lines changed

11 files changed

+485
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ My Springboot modules
2424
- [x] 19. [Springboot集成SpringRestdocs生成Api文档](https://github.com/zhangyd-c/springboot/tree/master/springboot-restdocs)
2525
- [x] 20. [Springboot开启HTTPS](https://github.com/zhangyd-c/springboot/tree/master/springboot-ssl)
2626
- [x] 21. [Springboot整合Swagger2](https://github.com/zhangyd-c/springboot/tree/master/springboot-swagger)
27+
- [x] 21. [Springboot使用Validator校验](https://github.com/zhangyd-c/springboot/tree/master/springboot-validator)
2728

2829
## 生命不息,折腾不止!
2930
### 更多信息,请关注:
@@ -36,5 +37,5 @@ My Springboot modules
3637
### 有任何问题可以
3738
- [new issue](https://github.com/zhangyd-c/springboot/issues)
3839
- [给我留言](http://www.flyat.cc/guestbook)
39-
40+
- [![qq](http://pub.idqqimg.com/wpa/images/group.png "加入QQ群")](http://shang.qq.com/wpa/qunwpa?idkey=818382ba0fc222dffc0da6f71aa207bfaf93bafb856e1c852e56de5911cb4c19)
4041
### 如果喜欢,请多多分享、多多Star

pom.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
<module>springboot-docker</module>
2828
<module>springboot-swagger</module>
2929
<module>springboot-interceptor</module>
30+
<module>springboot-validator</module>
3031
</modules>
3132

3233
<parent>

springboot-validator/README.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Springboot + validator 2017-10-10
2+
3+
### 前言
4+
5+
> The method validation feature supported by Bean Validation 1.1 is automatically enabled as long as a JSR-303 implementation (e.g. Hibernate validator) is on the classpath. This allows bean methods to be annotated with `javax.validation` constraints on their parameters and/or on their return value. Target classes with such annotated methods need to be annotated with the `@Validated` annotation at the type level for their methods to be searched for inline constraint annotations.
6+
7+
#### 常用注解
8+
9+
> @Null 只能是null
10+
@NotNull 不能为null 注意用在基本类型上无效,基本类型有默认初始值
11+
@AssertFalse 必须为false
12+
@AssertTrue 必须是true
13+
14+
> 字符串/数组/集合检查:(字符串本身就是个数组)
15+
@Pattern(regexp="reg") 验证字符串满足正则
16+
@Size(max, min) 验证字符串、数组、集合长度范围
17+
@NotEmpty 验证字符串不为空或者null
18+
@NotBlank 验证字符串不为null或者trim()后不为空
19+
20+
> 数值检查:同时能验证一个字符串是否是满足限制的数字的字符串
21+
@Max 规定值得上限int
22+
@Min 规定值得下限
23+
@DecimalMax("10.8") 以传入字符串构建一个BigDecimal,规定值要小于这个值
24+
@DecimalMin 可以用来限制浮点数大小
25+
@Digits(int1, int2) 限制一个小数,整数精度小于int1;小数部分精度小于int2
26+
@Digits 无参数,验证字符串是否合法
27+
@Range(min=long1,max=long2) 检查数字是否在范围之间
28+
这些都包括边界值
29+
30+
> 日期检查:Date/Calendar
31+
@Past 限定一个日期,日期必须是过去的日期
32+
@Future 限定一个日期,日期必须是未来的日期
33+
34+
> 其他验证:
35+
@Vaild 递归验证,用于对象、数组和集合,会对对象的元素、数组的元素进行一一校验
36+
@Email 用于验证一个字符串是否是一个合法的右键地址,空字符串或null算验证通过
37+
@URL(protocol=,host=,port=,regexp=,flags=) 用于校验一个字符串是否是合法URL
38+
39+
#### 注意
40+
41+
@Validated 和 BindingResult 是一一对应的,如果有多个@Validated,那么每个@Validated后面跟着的BindingResult就是这个@Validated的验证结果,顺序不能乱,比如
42+
43+
````
44+
@RequestMapping("/saveUser")
45+
public ModelAndView saveUser(@Validated User user, BindingResult userResult, @Validated Other other, BindingResult otherResult, Model model) {
46+
......
47+
}
48+
````
49+
userResult对应user实体类的校验结果,otherResult对应other类的校验结果
50+
#### 如下异常
51+
```
52+
HV000030: No validator could be found for constraint 'javax.validation.constraints.Pattern' validating type 'java.lang.Integer'. Check configuration for 'phone'
53+
```
54+
定义属性时将phone类型设置为Integer了, @Pattern只能作用于String类型的属性,所以报上面的错。
55+
56+
57+
#### 更多...
58+
59+
[https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-validation](https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-validation)

springboot-validator/pom.xml

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3+
<parent>
4+
<artifactId>springboot</artifactId>
5+
<groupId>com.zyd</groupId>
6+
<version>0.0.1-SNAPSHOT</version>
7+
</parent>
8+
<modelVersion>4.0.0</modelVersion>
9+
10+
<artifactId>springboot-validator</artifactId>
11+
<packaging>jar</packaging>
12+
13+
<name>springboot-validator</name>
14+
<url>http://maven.apache.org</url>
15+
16+
<properties>
17+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
18+
</properties>
19+
20+
<dependencies>
21+
<dependency>
22+
<groupId>org.springframework.boot</groupId>
23+
<artifactId>spring-boot-starter-freemarker</artifactId>
24+
</dependency>
25+
</dependencies>
26+
</project>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package com.zyd;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
6+
@SpringBootApplication
7+
public class Applaction {
8+
public static void main(String[] args) throws Exception {
9+
SpringApplication.run(Applaction.class, args);
10+
}
11+
}
12+
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Copyright [2016-2017] [yadong.zhang]
3+
* <p>
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
* <p>
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
* <p>
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package com.zyd.config;
17+
18+
import org.springframework.context.annotation.Configuration;
19+
import org.springframework.core.annotation.Order;
20+
import org.springframework.validation.MessageCodesResolver;
21+
import org.springframework.validation.Validator;
22+
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
23+
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
24+
25+
/**
26+
* springboot
27+
* Created by yadong.zhang on com.zyd.config
28+
* @Author: yadong.zhang
29+
* @Date: 2017/10/10 13:43
30+
*/
31+
@Configuration
32+
@Order(0)
33+
public class ValidatorConfig extends WebMvcConfigurerAdapter {
34+
35+
@Override
36+
public Validator getValidator() {
37+
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
38+
return bean;
39+
}
40+
41+
@Override
42+
public MessageCodesResolver getMessageCodesResolver() {
43+
return null;
44+
}
45+
}
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/**
2+
* Copyright [2016-2017] [yadong.zhang]
3+
* <p>
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
* <p>
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
* <p>
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package com.zyd.controller;
17+
18+
import com.zyd.model.Other;
19+
import com.zyd.model.User;
20+
import org.springframework.stereotype.Controller;
21+
import org.springframework.ui.Model;
22+
import org.springframework.validation.BindingResult;
23+
import org.springframework.validation.FieldError;
24+
import org.springframework.validation.annotation.Validated;
25+
import org.springframework.web.bind.annotation.RequestMapping;
26+
import org.springframework.web.servlet.ModelAndView;
27+
28+
import java.util.ArrayList;
29+
import java.util.HashMap;
30+
import java.util.List;
31+
import java.util.Map;
32+
33+
/**
34+
* springboot
35+
* Created by yadong.zhang on com.zyd.controller
36+
*
37+
* @Author: yadong.zhang
38+
* @Date: 2017/10/10 13:41
39+
*/
40+
@Controller
41+
public class IndexController {
42+
43+
@RequestMapping("/")
44+
public ModelAndView index() {
45+
46+
return new ModelAndView("index");
47+
}
48+
49+
@RequestMapping("/saveUser")
50+
public ModelAndView saveUser(@Validated User user, BindingResult userResult, @Validated Other other, BindingResult otherResult, Model model) {
51+
List<Map<String, String>> errorList = new ArrayList<>();
52+
53+
loadErrorList(userResult, errorList);
54+
loadErrorList(otherResult, errorList);
55+
56+
model.addAttribute("user", user);
57+
model.addAttribute("other", other);
58+
model.addAttribute("errorList", errorList);
59+
return new ModelAndView("index");
60+
}
61+
62+
private void loadErrorList(BindingResult userResult, List<Map<String, String>> errorList) {
63+
Map<String, String> map = null;
64+
if (userResult.hasErrors()) {
65+
List<FieldError> errors = userResult.getFieldErrors();
66+
for (FieldError error : errors) {
67+
map = new HashMap<String, String>();
68+
map.put("field", error.getField());
69+
map.put("message", error.getDefaultMessage());
70+
errorList.add(map);
71+
}
72+
}
73+
}
74+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
* Copyright [2016-2017] [yadong.zhang]
3+
* <p>
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
* <p>
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
* <p>
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package com.zyd.model;
17+
18+
import org.hibernate.validator.constraints.Length;
19+
20+
import javax.validation.constraints.Pattern;
21+
22+
/**
23+
* springboot
24+
* Created by yadong.zhang on com.zyd.model
25+
*
26+
* @Author: yadong.zhang
27+
* @Date: 2017/10/10 13:45
28+
*/
29+
public class Other {
30+
31+
@Length(max = 18, min = 15, message = "身份证长度为15或者18位")
32+
private String idcard;
33+
34+
@Pattern(regexp = "[0-9]{11}", message = "手机号格式错误")
35+
private String phone;
36+
37+
public String getIdcard() {
38+
return idcard;
39+
}
40+
41+
public void setIdcard(String idcard) {
42+
this.idcard = idcard;
43+
}
44+
45+
public String getPhone() {
46+
return phone;
47+
}
48+
49+
public void setPhone(String phone) {
50+
this.phone = phone;
51+
}
52+
53+
@Override
54+
public String toString() {
55+
return "Other{" +
56+
"idcard='" + idcard + '\'' +
57+
", phone=" + phone +
58+
'}';
59+
}
60+
}

0 commit comments

Comments
 (0)