在系列SpringMVC(4)数据绑定-1SpringMVC(5)数据绑定-2中我们展示了如何绑定数据,绑定完数据之后如何确保我们得到的数据的正确性?这就是我们本篇要说的内容
—> 数据验证。

这里我们采用Hibernate-validator来进行验证,Hibernate-validator实现了JSR-303验证框架支持注解风格的验证。首先我们要到http://hibernate.org/validator/下载需要的jar包,这里以4.3.1.Final作为演示,解压后把hibernate-validator-4.3.1.Final.jar、jboss-logging-3.1.0.jar、validation-api-1.0.0.GA.jar这三个包添加到项目中。

配置之前项目中的springservlet-config.xml文件,如下:

<!-- 默认的注解映射的支持 -->
<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>

其中<property name="basename" value="classpath:validatemessages"/>中的classpath:validatemessages为注解验证消息所在的文件,需要我们在resources文件夹下添加。

在com.demo.web.controllers包中添加一个ValidateController.java内容如下:

package com.demo.web.controllers;

import java.security.NoSuchAlgorithmException;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.demo.web.models.ValidateModel; @Controller
@RequestMapping(value = "/validate")
public class ValidateController { @RequestMapping(value="/test", method = {RequestMethod.GET})
public String test(Model model){ if(!model.containsAttribute("contentModel")){
model.addAttribute("contentModel", new ValidateModel());
}
return "validatetest";
} @RequestMapping(value="/test", method = {RequestMethod.POST})
public String test(Model model, @Valid @ModelAttribute("contentModel") ValidateModel validateModel, BindingResult result) throws NoSuchAlgorithmException{ //如果有验证错误 返回到form页面
if(result.hasErrors())
return test(model);
return "validatesuccess";
} }

其中@Valid @ModelAttribute("contentModel") ValidateModel validateModel的@Valid 意思是在把数据绑定到@ModelAttribute("contentModel") 后就进行验证。

在com.demo.web.models包中添加一个ValidateModel.java内容如下:

package com.demo.web.models;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range; public class ValidateModel{ @NotEmpty(message="{name.not.empty}")
private String name;
@Range(min=0, max=150,message="{age.not.inrange}")
private String age;
@NotEmpty(message="{email.not.empty}")
@Email(message="{email.not.correct}")
private String email; public void setName(String name){
this.name=name;
}
public void setAge(String age){
this.age=age;
}
public void setEmail(String email){
this.email=email;
} public String getName(){
return this.name;
}
public String getAge(){
return this.age;
}
public String getEmail(){
return this.email;
} }

在注解验证消息所在的文件即validatemessages.properties文件中添加以下内容:

name.not.empty=\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A\u3002
age.not.inrange=\u5E74\u9F84\u8D85\u51FA\u8303\u56F4\u3002
email.not.correct=\u90AE\u7BB1\u5730\u5740\u4E0D\u6B63\u786E\u3002
email.not.empty=\u7535\u5B50\u90AE\u4EF6\u4E0D\u80FD\u60DF\u6050\u3002

其中name.not.empty等分别对应了ValidateModel.java文件中message=”xxx”中的xxx名称,后面的内容是在输入中文是自动转换的ASCII编码,当然你也可以直接把xxx写成提示内容,而不用另建一个validatemessages.properties文件再添加,但这是不正确的做法,因为这样硬编码的话就没有办法进行国际化了。

在views文件夹中添加validatetest.jsp和validatesuccess.jsp两个视图,内容分别如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form:form modelAttribute="contentModel" method="post"> <form:errors path="*"></form:errors><br/><br/> name:<form:input path="name" /><br/>
<form:errors path="name"></form:errors><br/> age:<form:input path="age" /><br/>
<form:errors path="age"></form:errors><br/> email:<form:input path="email" /><br/>
<form:errors path="email"></form:errors><br/> <input type="submit" value="Submit" /> </form:form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
验证成功!
</body>
</html>

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

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

运行测试:

直接点击提交:

可以看到正确显示了设置的错误信息。

填写错误数据提交:

可以看到依然正确显示了设置的错误信息。

填写正确数据提交:

可以看到验证成功。

下面是主要的验证注解及说明:

注解

适用的数据类型

说明

@AssertFalse

Boolean, boolean

验证注解的元素值是false

@AssertTrue

Boolean, boolean

验证注解的元素值是true

@DecimalMax(value=x)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

验证注解的元素值小于等于@ DecimalMax指定的value值

@DecimalMin(value=x)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

验证注解的元素值小于等于@ DecimalMin指定的value值

@Digits(integer=整数位数, fraction=小数位数)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

验证注解的元素值的整数位数和小数位数上限

@Future

java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda
Time
 date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.

验证注解的元素值(日期类型)比当前时间晚

@Max(value=x)

BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type ofCharSequence (the numeric value represented
by the character sequence is evaluated), any sub-type of Number.

验证注解的元素值小于等于@Max指定的value值

@Min(value=x)

BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of CharSequence (the numeric value represented
by the char sequence is evaluated), any sub-type of Number.

验证注解的元素值大于等于@Min指定的value值

@NotNull

Any type

验证注解的元素值不是null

@Null

Any type

验证注解的元素值是null

@Past

java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda
Time
 date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.

验证注解的元素值(日期类型)比当前时间早

@Pattern(regex=正则表达式, flag=)

String. Additionally supported by HV: any sub-type of CharSequence.

验证注解的元素值与指定的正则表达式匹配

@Size(min=最小值, max=最大值)

String, Collection, Map and arrays. Additionally supported by HV: any sub-type of CharSequence.

验证注解的元素值的在min和max(包含)指定区间之内,如字符长度、集合大小

@Valid

Any non-primitive type(引用类型)

验证关联的对象,如账户对象里有一个订单对象,指定验证订单对象

@NotEmpty

CharSequence,CollectionMap and Arrays

验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)

@Range(min=最小值, max=最大值)

CharSequence, Collection, Map and Arrays,BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types

验证注解的元素值在最小值和最大值之间

@NotBlank

CharSequence

验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格

@Length(min=下限, max=上限)

CharSequence

验证注解的元素值长度在min和max区间内

@Email

CharSequence

验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式

更多信息请参考官方文档:http://docs.jboss.org/hibernate/validator/4.3/reference/en-US/html/validator-usingvalidator.html

SpringMVC(6)数据验证的更多相关文章

  1. 15.SpringMVC核心技术-数据验证

    在 Web 应用程序中,为了防止客户端传来的数据引发程序的异常,常常需要对数据进行验证. 输入验证分为客户端验证与服务器端验证.客户端验证主要通过 JavaScript 脚本进 行, 而服务器端验证则 ...

  2. SpringMVC学习笔记七:SpringMVC的数据验证

    SpringMVC支持JSR(Java Specification Requests, Java规范提案)303-Bean Validation数据验证规范,该规范的实现者很多,其中较常用的是 Hib ...

  3. SpringMVC配置数据验证(JSR-303)

    这篇文章已经过时了. 请参考比较合适的前后端交互方式. 1.pom.xml中追加hibernate-validator 2.在dto类的域上追加JSR-303的注解 public class Data ...

  4. springmvc 整合数据验证框架 jsr

    1.maven <dependency> <groupId>javax.validation</groupId> <artifactId>validat ...

  5. springMVC数据验证出现404错误解决办法

    今天使用springMVC的数据验证的时候,看似很简单的东西,却有一个很大的陷阱:提交空表单的时候总是出现404错误,但是后台却不给你报任何错.遇到这个错误这个很苦恼,搞了几小时,今天记录并分享一下解 ...

  6. SpringMVC数据验证

    SpringMVC数据验证——第七章 注解式控制器的数据验证.类型转换及格式化——跟着开涛学SpringMVC 资源来自:http://jinnianshilongnian.iteye.com/blo ...

  7. SpringMVC数据验证(AOP处理Errors和方法验证)

    什么是JSR303? JSR 303 – Bean Validation 是一个数据验证的规范,2009 年 11 月确定最终方案. Hibernate Validator 是 Bean Valida ...

  8. springmvc 数据验证 hibernate-validator --->对象验证

    数据验证步骤: 1.测试环境的搭建: 2.验证器的注册 在springmvc.xml配置文件中加以下代码: 3.验证注解添加到对应实体类上 4.修改处理器 5.将验证失败信息写入到表单 index.j ...

  9. SpringMVC使用@Valid注解进行数据验证

    SpringMVC使用@Valid注解进行数据验证   from:https://blog.csdn.net/zknxx/article/details/52426771 我们在做Form表单提交的时 ...

随机推荐

  1. Redis 主从架构搭建

    引言 准备搭建的是主从架构( Master/Slave )中的一主两从模式:其中 Master 为 Redis 的主服务器,主要负责写操作,两个 Slave 为 Redis 的从服务器,主要负责读操作 ...

  2. mysql基础之mariadb的安装,连接,用户,密码,权限设置语句详解

    一.mariadb安装 1.配置mariadb源: [root@ren7 ~]# vim /etc/yum.repos.d/mariadb.repo [mariadb] name = MariaDB ...

  3. shell基础之exit,break,continue

    exit代码: 1 #!/bin/bash 2 echo "Is it morning? Please answer yes or no." 3 read YES_OR_NO 4 ...

  4. linux 进程信号集合 sigset_t -(转自linengeir的专栏)

    sigset_t 号集及信号集操作函数:信号集被定义为一种数据类型: typedef struct { unsigned long sig[_NSIG_WORDS]: } sigset_t 信号集用来 ...

  5. C语言进阶日志二

    1.一个功能模块最好使用一个文件夹包含 2.基本就需要几个文件,比如定时器取反  LED: bsp_led.c 和 bsp_led.h : 包含你需要的led外设GPIO的初始化代码 led_it.c ...

  6. 修改mysql中数据库存储主路径

    一.首先把mysql的服务先停掉. 二.更改MySQL配置文件My.ini中的数据库存储主路径 打开文件夹C:\ProgramData\MySQL\MySQL Server 5.7中的my.ini文件 ...

  7. Jmeter——元件扩展,使其功能更全面

    工具扩展 在之前的博文中,有介绍自定义函数.Java请求扩展,博文如下: Jmeter二次开发--基于Java请求 Jmeter二次开发--自定义函数 上述内容,是按自己的需要来进行针对性扩展,从而实 ...

  8. 将代码生成器带入TVM

    将代码生成器带入TVM 为了使数据科学家不必担心开发新模型时的性能,硬件后端提供程序(例如Intel,NVIDIA,ARM等)可以提供诸如cuBLAS或cuDNN之类的内核库以及许多常用的深度学习内核 ...

  9. Tensor基础实践

    Tensor基础实践 飞桨(PaddlePaddle,以下简称Paddle)和其他深度学习框架一样,使用Tensor来表示数据,在神经网络中传递的数据均为Tensor. Tensor可以将其理解为多维 ...

  10. 使用现代C++如何避免bugs(上)

    使用现代C++如何避免bugs(上) How to avoid bugs using modern C++ C++的主要问题之一是拥有大量的构造,它们的行为是未定义的,或者程序员只是意想不到的.在各种 ...