spring mVC提供了很方便的校验,如下:
(1)依赖包:
validation-api.jar hibernate-validator.jar
通过maven引入
<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.1.2.Final</version> </dependency>
(2)要验证的实体类
import javax.validation.constraints.AssertFalse; import javax.validation.constraints.AssertTrue; import javax.validation.constraints.DecimalMax; import javax.validation.constraints.DecimalMin; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; public class Person { @NotNull(message = "用户名称不能为空") private String name; @Max(value = 100, message = "年龄不能大于100岁") @Min(value= 18 ,message= "必须年满18岁!" ) private int age; //必须是ture @AssertTrue(message = "bln4 must is true") private boolean bln; //必须是false @AssertFalse(message = "blnf must is falase") private boolean blnf; @DecimalMax(value="100",message="decim最大值是100") private int decimax; @DecimalMin(value="100",message="decim最小值是100") private int decimin; // @Length(min=1,max=5,message="slen长度必须在1~5个字符之间") private String slen; @NotNull(message = "身份证不能为空") @Pattern(regexp="^(\\d{18,18}|\\d{15,15}|(\\d{17,17}[x|X]))$", message="身份证格式错误") private String iDCard; @NotNull(message="密码不能为空") private String password; @NotNull(message="验证密码不能为空") private String rpassword; get/set方法 }
(3)构建controller如下
@Controller public class SpringValidatorTest { @RequestMapping("/validator/springtest") public void springte(@Valid Person person,BindingResult result){ if(result.hasErrors()){ List<ObjectError> list = result.getAllErrors(); for(ObjectError error: list){ //System.out.println(error.getObjectName()); //System.out.println(error.getArguments()[0]); System.out.println(error.getDefaultMessage());//验证信息 } } } }
(4)使用场景:添加或提交修改时进行字段的校验
登录:
注意:BindingResult一定要紧跟在实体类的后面,否则报错:
HTTP Status 400 -
type Status report
message
description The request sent by the client was syntactically incorrect.
Apache Tomcat/7.0.53
错误的代码:
@RequestMapping(value = "/add",method=RequestMethod.POST) public String addSaveNews(@Valid RoleLevel roleLevel, Model model, BindingResult binding) { if(binding.hasErrors()){ model.addAttribute(roleLevel); return jspFolder+"/add"; } saveCommon(roleLevel, model); return redirectViewAll; }
正确的代码:
@RequestMapping(value = "/add",method=RequestMethod.POST) public String addSaveNews(@Valid RoleLevel roleLevel, BindingResult binding, Model model) { if(binding.hasErrors()){ model.addAttribute(roleLevel); return jspFolder+"/add"; } saveCommon(roleLevel, model); return redirectViewAll; }
官方资料
Constraints in Bean Validation are expressed via Java annotations. In this section you will learn how to enhance an object model with these annotations. There are the following three types of bean constraints:
Note
Not all constraints can be placed on all of these levels. In fact, none of the default constraints defined by Bean Validation can be placed at class level. Thejava.lang.annotation.Target
annotation in the constraint annotation itself determines on which elements a constraint can be placed. See Chapter 6, Creating custom constraints for more information.
Constraints can be expressed by annotating a field of a class. Example 2.1, “Field-level constraints”shows a field level configuration example:
Example 2.1. Field-level constraints
package org.hibernate.validator.referenceguide.chapter02.fieldlevel; public class Car { @NotNull private String manufacturer; @AssertTrue private boolean isRegistered; public Car(String manufacturer, boolean isRegistered) { this.manufacturer = manufacturer; this.isRegistered = isRegistered; } //getters and setters... }
When using field-level constraints field access strategy is used to access the value to be validated. This means the validation engine directly accesses the instance variable and does not invoke the property accessor method even if such an accessor exists.
Constraints can be applied to fields of any access type (public, private etc.). Constraints on static fields are not supported, though.
Tip
When validating byte code enhanced objects property level constraints should be used, because the byte code enhancing library won't be able to determine a field access via reflection.
If your model class adheres to the JavaBeans standard, it is also possible to annotate the properties of a bean class instead of its fields. Example 2.2, “Property-level constraints” uses the same entity as inExample 2.1, “Field-level constraints”, however, property level constraints are used.
Example 2.2. Property-level constraints
package org.hibernate.validator.referenceguide.chapter02.propertylevel; public class Car { private String manufacturer; private boolean isRegistered; public Car(String manufacturer, boolean isRegistered) { this.manufacturer = manufacturer; this.isRegistered = isRegistered; } @NotNull public String getManufacturer() { return manufacturer; } public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } @AssertTrue public boolean isRegistered() { return isRegistered; } public void setRegistered(boolean isRegistered) { this.isRegistered = isRegistered; } }
Note
The property's getter method has to be annotated, not its setter. That way also read-only properties can be constrained which have no setter method.
When using property level constraints property access strategy is used to access the value to be validated, i.e. the validation engine accesses the state via the property accessor method.
Tip
It is recommended to stick either to field or property annotations within one class. It is not recommended to annotate a field and the accompanying getter method as this would cause the field to be validated twice.
Last but not least, a constraint can also be placed on the class level. In this case not a single property is subject of the validation but the complete object. Class-level constraints are useful if the validation depends on a correlation between several properties of an object.
The Car
class in Example 2.3, “Class-level constraint” has the two attributes seatCount
and passengers
and it should be ensured that the list of passengers has not more entries than seats are available. For that purpose the @ValidPassengerCount
constraint is added on the class level. The validator of that constraint has access to the complete Car
object, allowing to compare the numbers of seats and passengers.
Refer to Section 6.2, “Class-level constraints” to learn in detail how to implement this custom constraint.
Example 2.3. Class-level constraint
package org.hibernate.validator.referenceguide.chapter02.classlevel; @ValidPassengerCount public class Car { private int seatCount; private List<Person> passengers; //... }
参考:http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html/
http://www.yunmasoft.com
http://blog.csdn.net/xpsharp/article/details/9366865
相关推荐
spring mvc校验框架所需的几个jar包hibernate-validator-6.0.7.Final.jar、logging-3.1.0.CR2.jar、validator-api-2.0.2.jar
spring_validator验证 基业spring mvc3.0注解验证
我的博客中的《Spring MVC、hibernate validator和i18n》文章描述的项目的源代码,该文是对Spring mvc, validation和i18n的一个入门级的tutorial。我的博客地址是http://blog.csdn.net/zjysource
Maven+Spring MVC +Hibernate Validate(服务端验证) 增删改 ajax请求 文件上传
ssm(spring+spring mvc+mybatis)高仿小米电子商城项目实例 开发环境:Eclipse ,JDK 1.8 ,Tomcat7 技术选型: 后端技术 核心框架:Spring Framework 4.3.5 视图框架:Spring MVC 4.3.5 任务调度:Spring + ...
视图框架:Spring MVC 4.3.5 任务调度:Spring + Quartz 2.2.3 持久层框架:MyBatis 3.4.2 + Mybatis-plus 2.0.1 日志管理:SLF4J 1.7 + Log4j2 2.7 工具类:Apache Commons、Jackson 2.2、fastjson 1.2.20 前端技术...
自己搭建的简单的Spring + Spring MVC + Mybatis框架 功能比较简单但是比较实用 初学者适用 需项目使用的请自行添加功能 集成功能 1.提供分页参数自动查询总数 2.实体校验(hibernate-validator) 3.单用户登录(监听...
用Spring MVC+hibernate 写的一个HelloWorld小实例,加入了一个简单验证。
视图框架:Spring MVC 4.3.5 任务调度:Spring + Quartz 2.2.3 持久层框架:MyBatis 3.4.2 + Mybatis-plus 2.0.1 数据库连接池:Alibaba Druid 1.0 缓存框架:Ehcache 2.6 + Redis 2.9.0 日志管理:SLF4J 1.7 + Log4...
数据库和配置MySQL 飞路(用于数据迁移) GradleTomcat吉特Google Book API 后端技术JavaSpring MVC,Spring AOP,Spring Security Hibernate ORM,Hibernate Validator,Hibenrate Search(Lucene) 翻新,JSON ...
主要给大家介绍了关于Spring MVC+FastJson+hibernate-validator整合的完整实例教程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
整合hibernate.validator校验器对controller接口参数进行校验 使用了springmvc统一异常处理 使用了FormattingConversionServiceFactoryBean对于传入参数中日期或数字字符串进行数据转换和数据格式化 使用了...
本示例中使用了以下功能: Spring MVC Portlet 动作和渲染映射依赖注入(使用@Inject) 表单绑定表单验证(Hibernate Validator)入门第 1 步:安装先决条件:安装(EXO_TOMCAT_ROOT_FOLDER 将用于指定 eXo Tomcat ...
Spring MVC(Model-View-Controller)是一个基于Java的MVC(模型-视图-控制器)框架,用于构建Web应用程序。它是Spring Framework的一部分,提供了一种简单、灵活且可扩展的方式来开发Web应用程序。 下面是Spring ...
springmvc 校验时所需要的三个包validation-api.jar hibernate-validator-4.1final.jar jbosslogin.jar !解决了tomcat启动的时候报错: classnotfound:javax.validation.constraint的错误!
表单数据采用bootstrapValidator校验,简单快捷方便 运行环境 jdk8+mysql+redis+IntelliJ IDEA+maven 项目技术(必填) Springboot+Mybatis+ SpringMvc+springsecrity+Redis+bootstrap+jquery 数据库文件 压缩包...
- Validation using JSR 303 (Bean Validation API) annotations and Spring's Validator interface - SpEL (Spring Expression Language) - Caching using Spring's cache abstraction - Sending and receiving JMS...
视图框架:Spring MVC 服务端验证:Blade Validator 任务调度:Spring Task 持久层框架:beetlsql 模板引擎:beetl 数据库连接池:Alibaba Druid 缓存框架:Ehcache 日志管理:SLF4J、LOGBACKUP 工具类:...
清晰的角色划分:控制器(controller)、验证器(validator)、 命令对象(command object)、表单对象(form object)、模型对象(model object)、 Servlet分发器(DispatcherServlet)、 处理器映射(handler ...
Spring MVC 入门 从一个最简单的 Spring Web 应用程式,来看看 Spring MVC 框架的架构与 API 组成元素。 第一个 Spring MVC 程式 WebApplicationContext Handler Mapping Handler ...