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

作者:jingxian 时间:2023-11-14 21:44:05 

数据校验在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)验证属性值必须在合适的范围内

三、修改实体类

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


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...  
}

四、修改相应的处理方法


@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";
}

五、视图输出

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


<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


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. 实体类中的注解使用相对引用


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. 修改配置文件


<!-- 默认的注解映射的支持 -->
 <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,数据校验
0
投稿

猜你喜欢

  • Android使用shape使组件呈现出特殊效果的方法

    2022-06-28 03:42:27
  • 集合嵌套之ArrayList嵌套ArrayList实例

    2021-06-23 07:32:25
  • 详解J2EE开发的网站部署到阿里云服务器的方法

    2022-06-21 07:50:16
  • Springboot启动流程详细分析

    2023-11-29 00:23:10
  • 深入探索Java常量池

    2022-12-28 00:55:53
  • android 动态控制状态栏显示和隐藏的方法实例

    2023-07-08 10:11:43
  • Android NotificationListenerService 通知服务原理解析

    2022-03-29 05:34:29
  • Android UI之ImageView实现图片旋转和缩放

    2023-08-04 02:53:39
  • Spring创建Bean的过程Debug的详细流程

    2023-02-09 23:55:37
  • java 实现比较版本号功能

    2022-08-12 20:35:11
  • SpringBoot自动配置原理分析

    2022-03-02 17:42:51
  • Spring Boot中lombok的安装与使用详解

    2021-08-26 14:50:38
  • 使用C# 的webBrowser写模拟器时的javascript脚本调用问题

    2022-03-14 23:56:31
  • Java算法实战之排一亿个随机数

    2022-11-22 02:47:26
  • Android 逆向学习详解及实例

    2022-12-26 08:51:50
  • Spring中Bean的生命周期使用解析

    2021-09-06 23:06:54
  • c#连接mdf文件示例分享

    2022-12-15 10:48:33
  • Android 网络请求框架Volley实例详解

    2023-08-11 07:00:18
  • SpringBoot中获取微信用户信息的方法

    2023-05-26 21:40:55
  • C#中WebBrowser.DocumentCompleted事件多次调用问题解决方法

    2023-12-05 18:23:15
  • asp之家 软件编程 m.aspxhome.com