Spring MVC+FastJson+hibernate-validator整合的完整实例教程

2025-05-29 0 55

一:hibernate-validator 基础

1. 简介:

通过使用注解annotations 给类或者类的属性加上约束(constraint),在运行期检查属性值的合法性.

2. 作用:

在api接口开发中参数校验是非常重要的事情,因为客户端很可能会少传参数,或者值不合法,甚至参数值是恶意的,所以对客户端传来的参数的合法性就必须要校验了,其中将参数值的校验规则通过注解的形式注解到属性上是一种比较优雅的方式。

3. 常用的约束注解

  • @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(regex=,flag=) 被注释的元素必须符合指定的正则表达式
  • hibernate validator 附加的 constraint
  • @notblank(message =) 验证字符串非null,且长度必须大于0
  • @email 被注释的元素必须是电子邮箱地址
  • @length(min=,max=) 被注释的字符串的大小必须在指定的范围内
  • @notempty 被注释的字符串的必须非空
  • @range(min=,max=,message=) 被注释的元素必须在合适的范围内
  • @url(protocol=,host=, port=, regexp=, flags=) 被注释的字符串必须是一个有效的url
  • @creditcardnumber 被注释的字符串必须通过luhn校验算法,银行卡,信用卡等号码一般都用luhn计算合法性
  • @scriptassert(lang=, script=, alias=) 要有java scripting api 即jsr 223 (“scripting for the javatm platform”)的实现
  • @safehtml(whitelisttype=, additionaltags=) classpath中要有jsoup包

4. 初识hibernate-validator

?

1

2

3

4

5

6

7

8

9

10

11

12
public class address {

@notnull private string line1;

private string line2;

private string zip;

private string state;

@length(max = 20)

@notnull

private string country;

@range(min = -2, max = 50, message = "floor out of range")

public int floor;

// getter&&setter

}

二:整合校验 hibernate-validator

该示例是在springmvc+fastjson整合(https://www.zzvips.com/article/158724.html)基础上进行集成的,可以先看一下这篇文章(有源码供下载),在该文章的基础上整合hibernate-validator

整合步骤:

1、在pom.xml中引入hibernate-validator依赖

?

1

2

3

4

5
<dependency>

<groupid>org.hibernate</groupid>

<artifactid>hibernate-validator</artifactid>

<version>5.4.1.final</version>

</dependency>

2、在[xxx]-servlet.xml中配置验证器:hibernatevalidator

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37
<!-- <mvc:annotation-driven> 增加验证器属性validator="validator" -->

<mvc:annotation-driven validator="validator">

<mvc:message-converters register-defaults="true">

<!-- 配置fastjson 替换原来的jackson支持 -->

<bean class="com.alibaba.fastjson.support.spring.fastjsonhttpmessageconverter">

<property name="supportedmediatypes">

<list>

<value>text/html;charset=utf-8</value>

<value>application/json</value>

</list>

</property>

<property name="features">

<list>

<value>quotefieldnames</value>

<value>writemapnullvalue</value>

</list>

</property>

</bean>

</mvc:message-converters>

</mvc:annotation-driven>

<bean id="validator" class="org.springframework.validation.beanvalidation.localvalidatorfactorybean">

<property name="providerclass" value="org.hibernate.validator.hibernatevalidator"/>

<property name="validationmessagesource" ref="messagesource"/>

</bean>

<bean id="messagesource" class="org.springframework.context.support.reloadableresourcebundlemessagesource">

<property name="basenames">

<list>

<value>classpath:conf/settings/validation</value>

<value>classpath:org/hibernate/validator/validationmessages</value>

</list>

</property>

<property name="usecodeasdefaultmessage" value="false"/>

<property name="defaultencoding" value="utf-8"/>

<property name="cacheseconds" value="60"/>

</bean>

3、在src/main/resources/conf/settings位置定义验证消息文件描述 validation.properties

?

1

2

3

4

5

6

7
validation.common.not.null=该字段不能为空

validation.common.not.range=长度非法

validation.common.format.error=格式错误

validation.param.age=年龄未满18周岁

rep.error.unknown=未知错误

4、新建实体类以供测试

userentity

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100
package com.mengdee.manage.validator;

import javax.validation.constraints.min;

import javax.validation.constraints.notnull;

import javax.validation.constraints.null;

import javax.validation.constraints.pattern;

import org.hibernate.validator.constraints.email;

import org.hibernate.validator.constraints.length;

import org.hibernate.validator.constraints.notblank;

public class userentity {

@null(groups={groupa.class})

@notnull(groups={groupb.class})

@min(value = 1, message="id值必须大于0", groups={groupb.class})

private long id;

@notblank(groups={groupa.class, groupb.class})

@pattern(regexp="^(?![0-9]+$)(?![a-za-z]+$)[0-9a-za-z]{6,20}$", message="由6-21字母和数字组成,不能是纯数字或纯英文", groups={groupa.class, groupb.class})

private string password;

@notblank(groups={groupa.class, groupb.class})

@pattern(regexp="^((13[0-9])|(15[^4,\\\\d])|(18[0,3-9]))\\\\d{8}$", message="手机号格式不正确")

private string phone;

@notblank(groups={groupb.class})

@length(min=6, max=12, message="昵称长度为6到12位")

private string nickname;

@min(value=18, message="{validation.param.age}")

private int age;

@notblank(groups={groupa.class})

@email(message="{validation.common.format.error}")

private string email;

@notblank

@length(min=3, max=10, message="{validation.common.not.range}")

private string username;

public userentity() {

}

public long getid() {

return id;

}

public void setid(long id) {

this.id = id;

}

public string getnickname() {

return nickname;

}

public void setnickname(string nickname) {

this.nickname = nickname;

}

public int getage() {

return age;

}

public void setage(int age) {

this.age = age;

}

public string getemail() {

return email;

}

public void setemail(string email) {

this.email = email;

}

public string getpassword() {

return password;

}

public void setpassword(string password) {

this.password = password;

}

public string getusername() {

return username;

}

public void setusername(string username) {

this.username = username;

}

public string getphone() {

return phone;

}

public void setphone(string phone) {

this.phone = phone;

}

}

usermodel

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95
package com.mengdee.manage.validator;

import javax.validation.constraints.min;

import javax.validation.constraints.pattern;

import org.hibernate.validator.constraints.email;

import org.hibernate.validator.constraints.length;

import org.hibernate.validator.constraints.notblank;

public class usermodel {

@min(value = 1, message="id值必须大于0")

private long id;

@notblank

@length(min=6, max=12, message="昵称长度为6到12位")

private string nickname;

@min(value=18, message="{validation.param.age}")

private int age;

@notblank

@email(message="{validation.common.format.error}")

private string email;

@notblank

@pattern(regexp="^(?![0-9]+$)(?![a-za-z]+$)[0-9a-za-z]{6,20}$", message="由6-21字母和数字组成,不能是纯数字或纯英文")

private string password;

@notblank

@length(min=3, max=10, message="{validation.common.not.range}")

private string username;

@notblank

@pattern(regexp="^((13[0-9])|(15[^4,\\\\d])|(18[0,3-9]))\\\\d{8}$", message="手机号格式不正确")

private string phone;

public usermodel() {

}

public long getid() {

return id;

}

public void setid(long id) {

this.id = id;

}

public string getnickname() {

return nickname;

}

public void setnickname(string nickname) {

this.nickname = nickname;

}

public int getage() {

return age;

}

public void setage(int age) {

this.age = age;

}

public string getemail() {

return email;

}

public void setemail(string email) {

this.email = email;

}

public string getpassword() {

return password;

}

public void setpassword(string password) {

this.password = password;

}

public string getusername() {

return username;

}

public void setusername(string username) {

this.username = username;

}

public string getphone() {

return phone;

}

public void setphone(string phone) {

this.phone = phone;

}

}

userdetail :

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38
package com.mengdee.manage.validator;

import org.hibernate.validator.constraints.notblank;

public class userdetail {

private long id;

@notblank

private string address;

@notblank

private string company;

public userdetail() {

}

public long getid() {

return id;

}

public void setid(long id) {

this.id = id;

}

public string getaddress() {

return address;

}

public void setaddress(string address) {

this.address = address;

}

public string getcompany() {

return company;

}

public void setcompany(string company) {

this.company = company;

}

}

使用validcontroller 进行测试

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48
package com.mengdee.manage.controller;

import javax.servlet.http.httpservletrequest;

import javax.validation.valid;

import org.springframework.stereotype.controller;

import org.springframework.validation.bindingresult;

import org.springframework.validation.fielderror;

import org.springframework.web.bind.annotation.requestmapping;

import org.springframework.web.bind.annotation.requestmethod;

import org.springframework.web.bind.annotation.responsebody;

import com.mengdee.manage.validator.usermodel;

@controller

@requestmapping("/valid")

public class validcontroller extends basecontroller {

// http://localhost:8081/platform-springmvc-webapp/valid/test?age=18&nickname=mengdee&id=1&email=123@qq.com&password=root123&username=123&phone=18321758957

@requestmapping(value = "/test", method = requestmethod.get)

public @responsebody object validation(httpservletrequest request, @valid usermodel user, bindingresult bindingresult){

if (bindingresult.haserrors()) {

fielderror fielderror = bindingresult.getfielderror();

return super.responsejsonerror(fielderror);

}

return "ok";

}

// 一个方法同时校验多个对象需要绑定多个结果bindingresult,出现一个@valid就对应后面声明的一个bindingresult

@requestmapping(value = "/test2", method = requestmethod.get)

public @responsebody object validationmore(httpservletrequest request,

@valid usermodel user, bindingresult bindingresult,

@valid userdetail userdetail, bindingresult bindingresult2){

if (bindingresult.haserrors()) {

fielderror fielderror = bindingresult.getfielderror();

return super.responsejsonerror(fielderror);

}

if (bindingresult2.haserrors()) {

fielderror fielderror = bindingresult2.getfielderror();

return super.responsejsonerror(fielderror);

}

return "ok";

}

}

使用注意:

1、对于多个字段,系统验证的顺序好像和字段声明的顺序是不一样的,好像是无须的

2、对于每个验证如果没有message属性,系统会使用默认的,如对应@notblank相当于@notblank(message=”不能为空”)

3、对于引用类型如string等类型,一定要结合@notnull、@notempty或者@notblank来配合使用,如果不写空的约束,经测试,该字段是不参与校验的,如单独使用@pattern、@length、@email等是不会进行验证的,必须要使用空的约束来限制

@min:用于基本数据类型,如int、long等

@notnull: 任何对象的value不能为null

@notempty:集合对象的元素不为0,即集合不为空,也可以用于字符串不为null

@notblank:只能用于字符串不为null,并且字符串trim()以后length要大于0

三:分组校验@validated

  • @valid是属于javax.validation.valid里的。
  • @validated是@valid 的一次封装,是spring提供的校验机制使用(org.springframework.validation.annotation.validated) ,@valid不提供分组功能

1. 分组的作用(使用场景):

每个校验的注解约束都有一个groups属性,用于指定该约束是属于哪个组的,这样在同一个字段上就可以配置多套约束,在使用的时候只需要指定使用那套约束即可,例如对于注册用户和修改用户信息时,注册时id必须为空,修改用户信息时id必须不能为空,在使用的时候只需要将这两种约束分配到不同的组中即可,如添加时使用组a的约束,更新时使用组b的约束

2. 分组就是一个空接口interface

groupa 和 groupb

?

1

2

3

4

5

6

7
package com.mengdee.manage.validator;

public interface groupa {

}

package com.mengdee.manage.validator;

public interface groupb {

}

在使用时指定具体使用那套分组的约束@validated({groupa.class})

3. 组序列@groupsequence

默认情况下,不同组别的约束验证是无序的,组序列就是按照分组的前后顺序依次验证,如先验证groupa组的约束,再验证groupb组的约束。如果对组的校验顺序有要求,例如必须先校验a组再校验b组,可以使用@groupsequence来定义每个组的顺序

使用场景:

(1)第二个组中的约束验证依赖于一个稳定状态来运行,而这个稳定状态是由第一个组来进行验证的。

(2)某个组的验证比较耗时,cpu 和内存的使用率相对比较大,最优的选择是将其放在最后进行验证。因此,在进行组验证的时候尚需提供一种有序的验证方式,这就提出了组序列的概念。

一个组可以定义为其他组的序列,使用它进行验证的时候必须符合该序列规定的顺序。在使用组序列验证的时候,如果序列前边的组验证失败,则后面的组将不再给予验证。

使用注解groupsequence定义组序列:groupab

?

1

2

3

4
package com.mengdee.manage.validator;

import javax.validation.groupsequence;

@groupsequence({groupa.class, groupb.class})

public interface groupab {

validationcontroller

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85
package com.mengdee.manage.controller;

import javax.servlet.http.httpservletrequest;

import org.springframework.stereotype.controller;

import org.springframework.validation.bindingresult;

import org.springframework.validation.fielderror;

import org.springframework.validation.annotation.validated;

import org.springframework.web.bind.annotation.requestmapping;

import org.springframework.web.bind.annotation.requestmethod;

import org.springframework.web.bind.annotation.responsebody;

import com.mengdee.manage.validator.groupa;

import com.mengdee.manage.validator.groupab;

import com.mengdee.manage.validator.groupb;

import com.mengdee.manage.validator.userentity;

@controller

@requestmapping("/validated")

public class validationcontroller extends basecontroller {

// 校验时指定了groupa,那么只校验约束中包含groupa的约束,没有包含就不校验,例如对于phone, @notblank指定的分组,而@pattern没有指定分组,那么只校验空着一个约束,不校验手机号格式

// http://localhost:8081/platform-springmvc-webapp/validated/groupa?password=root123&phone=123

@requestmapping(value = "/groupa", method = requestmethod.get)

public @responsebody object groupa(httpservletrequest request, @validated({groupa.class}) userentity user, bindingresult bindingresult){

if (bindingresult.haserrors()) {

fielderror fielderror = bindingresult.getfielderror();

return this.responsejsonerror(fielderror);

}

return "ok";

}

// http://localhost:8081/platform-springmvc-webapp/validated/groupb?phone=123&password=root123&id=1

@requestmapping(value = "/groupb", method = requestmethod.get)

public @responsebody object groupb(httpservletrequest request, @validated({groupb.class}) userentity user, bindingresult bindingresult){

if (bindingresult.haserrors()) {

fielderror fielderror = bindingresult.getfielderror();

return this.responsejsonerror(fielderror);

}

return "ok";

}

// groupab

// http://localhost:8081/platform-springmvc-webapp/validated/groupab?phone=111&password=root123&nickname=123&email=xxx@qq.com

// @validated({groupa.class, groupb.class}):groupa和groupb的关系是或的关系,就像数据库中的or一样,只要满足一个条件就会对该约束进行校验,同时使用多个组注意多个组之间没有先后属性之说,并不是先校验组a,然后再校验组b

// 因为id的为空和不为空的约束都会进行检查,所以先注释掉该属性

@requestmapping(value = "/groupab", method = requestmethod.get)

public @responsebody object groupab(httpservletrequest request, @validated({groupa.class, groupb.class}) userentity user, bindingresult bindingresult){

if (bindingresult.haserrors()) {

fielderror fielderror = bindingresult.getfielderror();

return this.responsejsonerror(fielderror);

}

return "ok";

}

// default

// http://localhost:8081/platform-springmvc-webapp/default?email=xxx@163.com&age=18

// @validated 如果没有指定groups则验证没有分组的属性(此时和@valid功能一样),如果一个字段上有多个约束,都必须没有指定组,如果部分约束指定的组,部分约束没有指定约束,那么在使用@validated时不进行检查的

@requestmapping(value = "/default", method = requestmethod.get)

public @responsebody object defaultgroup(httpservletrequest request, @validated userentity user, bindingresult bindingresult){

if (bindingresult.haserrors()) {

fielderror fielderror = bindingresult.getfielderror();

return this.responsejsonerror(fielderror);

}

return "ok";

}

//localhost:8081/platform-springmvc-webapp/validated/sequence?phone=123&password=root123&email=123&nickname=123

// 对于一个属性上有多个约束,并且多个约束不都在同一个组,那么在检查的时候顺序是根据groupsequence定义的先后顺序来检查的

@requestmapping(value = "/sequence", method = requestmethod.get)

public @responsebody object sequence(httpservletrequest request, @validated({groupab.class}) userentity user, bindingresult bindingresult){

if (bindingresult.haserrors()) {

fielderror fielderror = bindingresult.getfielderror();

return this.responsejsonerror(fielderror);

}

return "ok";

}

}

四:自定义hibernate validation注解

当hibernate validation提供的注解不能满足需求时,可以自定义校验约束。

自定义注解约束步骤:

  • 创建注解
  • 创建注解对应的约束验证类
  • 使用注解
  • 测试注解

创建注解 @phone

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28
package com.mengdee.manage.validator;

import java.lang.annotation.target;

import javax.validation.constraint;

import javax.validation.payload;

import static java.lang.annotation.elementtype.annotation_type;

import static java.lang.annotation.elementtype.constructor;

import static java.lang.annotation.elementtype.field;

import static java.lang.annotation.elementtype.method;

import static java.lang.annotation.elementtype.parameter;

import static java.lang.annotation.retentionpolicy.runtime;

import java.lang.annotation.documented;

import java.lang.annotation.retention;

@target({method, field, annotation_type, constructor, parameter })

@retention(runtime)

@documented

@constraint(validatedby = {phoneconstraint.class})

public @interface phone {

string message() default "手机号格式错误";

string regexp() default "^((13[0-9])|(15[^4,\\\\d])|(18[0,3-9]))\\\\d{8}$";

class<?>[] groups() default {};

class<? extends payload>[] payload() default { };

@target({ method, field, annotation_type, constructor, parameter })

@retention(runtime)

@documented

public @interface list {

phone[] value();

}

}

创建手机号注解对应的约束验证类phoneconstraint

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22
package com.mengdee.manage.validator;

import javax.validation.constraintvalidator;

import javax.validation.constraintvalidatorcontext;

public class phoneconstraint implements constraintvalidator<phone, string> {

private string regexp;

@override

public void initialize(phone phoneannotation) {

this.regexp = phoneannotation.regexp();

}

@override

public boolean isvalid(string value, constraintvalidatorcontext context) {

if (value == null) {

return true; // hv000028: unexpected exception during isvalid call

}

if (value.matches(regexp)) {

return true;

}

return false;

}

}

在属性上使用注解@phone

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18
package com.mengdee.manage.validator;

import org.hibernate.validator.constraints.notblank;

public class userdetail {

@notblank

@phone

private string phone;

public userdetail() {

}

public string getphone() {

return phone;

}

public void setphone(string phone) {

this.phone = phone;

}

}

测试注解

?

1

2

3

4

5

6

7

8

9

10
// http://localhost:8081/platform-springmvc-webapp/valid/test3?address=123&company=456&phone=123

@requestmapping(value = "/test3", method = requestmethod.get)

public @responsebody object validationcustomannotation(httpservletrequest request,

@valid userdetail userdetail, bindingresult bindingresult){

if (bindingresult.haserrors()) {

fielderror fielderror = bindingresult.getfielderror();

return super.responsejsonerror(fielderror);

}

return "ok";

}

完整代码下载:platform-springmvc-webapp.rar

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对快网idc的支持。

参考文章:

  • hibernate validation文档:http://docs.jboss.org/hibernate/validator/5.2/reference/en-us/html_single/#validator-customconstraints:
  • 自定义注解:https://www.zzvips.com/article/102631.html
  • 深入理解java:注解(annotation)自定义注解入门:https://www.zzvips.com/article/155482.html

原文链接:https://blog.csdn.net/vbirdbest/article/details/72620957

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Spring MVC+FastJson+hibernate-validator整合的完整实例教程 https://www.kuaiidc.com/111703.html

相关文章

发表评论
暂无评论