SpringMVC 数据校验方法(必看篇)

2025-05-29 0 39

数据校验在web应用里是非常重要的功能,尤其是在表单输入中。在这里采用Hibernate-Vapdator进行校验,该方法实现了JSR-303验证框架支持注解风格的验证。

一、导入jar包

若要实现数据校验功能,需要导入必要的jar包,主要包括以下几个:

classmate-1.3.1.jar

hibernate-vapdator-5.4.1.Final.jar

hibernate-vapdator-annotation-processor-5.4.1.Final.jar

hibernate-vapdator-cdi-5.4.1.Final.jar

jboss-logging-3.3.0.Final.jar

vapdation-api-1.1.0.Final.jar

二、常用的校验注解

注解 功能
@Null 验证对象是否为 null
@NotNull 验证对象是否不为 null
@AssertTrue 验证 Boolean 对象是否为 true
@AssertTrue 验证 Boolean 对象是否为 false
@Max(value) 验证 Number 和 String 对象是否小于等于指定值
@Min(value) 验证 Number 和 String 对象是否大于等于指定值
@DecimalMax(value) 验证注解的元素值小于等于 @DecimalMax 指定的 value 值
@DecimalMin(value) 验证注解的元素值大于等于 @DecimalMin 指定的 value 值
@Digits(integer,fraction) 验证字符串是否符合指定格式的数字,integer 指定整数精度,fraction 指定小数精度
@Size(min,max) 验证对象长度是否在给定的范围内
@Past 验证 Date 和 Calendar 对象是否在当前时间之前
@Future 验证 Date 和 Calendar 对象是否在当前时间之后
@Pattern 验证 String 对象是否符合正则表达式的规则
@NotBlank 检查字符串是不是 Null,被 Trim 的长度是否大于0,只对字符串,且会去掉前后空格
@URL 验证是否是合法的 url
@Email 验证是否是合法的邮箱
@CreditCardNumber 验证是否是合法的信用卡号
@Length(min,max) 验证字符串的长度必须在指定范围内
@NotEmpty 检查元素是否为 Null 或 Empty
@Range(min,max,message) 验证属性值必须在合适的范围内

三、修改实体类

在类的属性上进行标注,如:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15
public class User {

@NotBlank(message = "Username can not be empty")

private String username;

@NotBlank(message = "password can not be blank")

@Length(min = 6, max = 16, message = "The length of the password must be between 6 and 16 bits")

private String password;

@Range(min = 18, max = 60, message = "Age must be between 18 and 60 years old")

private Integer age;

@Pattern(regexp = "^1[3|4|5|7|8][0-9]{9}$", message = "Please enter the correct format of the phone number")

private String phone;

@Email(message = "Please enter a valid email address")

private String email;

// other...

}

四、修改相应的处理方法

?

1

2

3

4

5

6

7

8
@RequestMapping(value = "/register")

public String register(@Valid @ModelAttribute("user") User user, Errors errors,Model model) {

if(errors.hasErrors()){

return "register";

}

model.addAttribute("user", user);

return "success";

}

五、视图输出

校验之后,我们通常需要在表单的输入框后进行文字反馈:

?

1

2

3

4

5

6

7

8

9

10

11
<form:form modelAttribute="user" method="post" action="register">

<fieldset>

<legend>register</legend>

<p>

<label>name:</label>

<form:input path="username" />

<form:errors path="username" cssStyle="color:red"/>

</p>

...

</fieldset>

</form:form>

然而,有些时候并不推荐直接将错误信息写在注解的message属性里,这样不方便国际化。因此可以做以下几处修改:

1. 新建validatemessages.properties

?

1

2

3

4

5

6
username.not.blank = "username cannot be empty..."

password.not.blank = "password cannot be empty"

password.not.length = "password should be in 6-10"

age.not.range = "age should be in 10-70"

phone.not.pattern = "phone should be in format"

email.not.format = "email should be in format"

2. 实体类中的注解使用相对引用

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20
public class User {

@NotBlank(message = "{username.not.blank}")

private String username;

@NotBlank(message = "{password.not.blank}")

@Length(min = 6, max = 10, message = "{password.not.length}")

private String password;

@Range(min = 10, max = 70, message = "{age.not.range}")

private Integer age;

@Pattern(regexp = "^1[3|4|5|7|8][0-9]{9}$", message = "{phone.not.pattern}")

private String phone;

@Email(message = "{email.not.format}")

private String email;

// other...

}

3. 修改配置文件

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14
<!-- 默认的注解映射的支持 -->

<mvc:annotation-driven validator="validator" conversion-service="conversion-service" />

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

<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>

<!--不设置则默认为classpath下的 ValidationMessages.properties -->

<property name="validationMessageSource" ref="validatemessageSource"/>

</bean>

<bean id="conversion-service" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />

<bean id="validatemessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">

<property name="basename" value="classpath:validatemessages"/>

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

<property name="cacheSeconds" value="120"/>

</bean>

特别注意:value="classpath:validatemessages",文件名不加后缀!

至此,数据校验的整个过程就结束了。

最后还要特别强调的重点是:

视图中<form:form modelAttribute="contentModel" method="post">的modelAttribute="xxx"后面的名称xxx必须与对应的@Valid @ModelAttribute("xxx") 中的xxx名称一致,否则模型数据和错误信息都绑定不到。

<form:errors path="name"></form:errors>即会显示模型对应属性的错误信息,当path="*"时则显示模型全部属性的错误信息。

以上这篇SpringMVC 数据校验方法(必看篇)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持快网idc。

收藏 (0) 打赏

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

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

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

快网idc优惠网 建站教程 SpringMVC 数据校验方法(必看篇) https://www.kuaiidc.com/115971.html

相关文章

发表评论
暂无评论