温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用SpringMVC怎么实现对数据进行校验

发布时间:2020-11-21 15:47:17 来源:亿速云 阅读:148 作者:Leah 栏目:编程语言

使用SpringMVC怎么实现对数据进行校验?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

一、导入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怎么实现对数据进行校验问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI