1、需要的jar包

2、springsevlet-config.xml配置

在spring3之后,任何支持JSR303的validator(如Hibernate Validator)都可以通过简单配置引入,只需要在配置xml中加入,这时validatemessage的属性文件默认为classpath下的ValidationMessages.properties

<!-- support JSR303 annotation if JSR 303 validation present on classpath -->
<mvc:annotation-driven />

如果不使用默认,可以使用下面配置:

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

<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="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>
 

3、hibernate validator constraint 注解

 Bean Validation 中内置的 constraint
@Null 被注释的元素必须为 null
@NotNull 被注释的元素必须不为 null
@AssertTrue 被注释的元素必须为 true
@AssertFalse 被注释的元素必须为 false
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max=, min=) 被注释的元素的大小必须在指定的范围内
@Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past 被注释的元素必须是一个过去的日期
@Future 被注释的元素必须是一个将来的日期
@Pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式 Hibernate Validator 附加的 constraint
@NotBlank(message =) 验证字符串非null,且长度必须大于0
@Email 被注释的元素必须是电子邮箱地址
@Length(min=,max=) 被注释的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串的必须非空
@Range(min=,max=,message=) 被注释的元素必须在合适的范围内

Demo:

  编写自己的验证类:

 package com.journaldev.spring.form.validator;

 import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator; import com.journaldev.spring.form.model.Employee;
/**
*自定义一个验证类由于对员工信息进项验证(实现Validator接口)
*/
public class EmployeeFormValidator implements Validator { //which objects can be validated by this validator
@Override
public boolean supports(Class<?> paramClass) {
return Employee.class.equals(paramClass);
}
//重写validate()方法编写验证规则
@Override
public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "id", "id.required"); Employee emp = (Employee) obj;
if(emp.getId() <=0){
errors.rejectValue("id", "negativeValue", new Object[]{"'id'"}, "id can't be negative");
} ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "role", "role.required");
}
}

  控制器代码:

 package com.journaldev.spring.form.controllers;

 import java.util.HashMap;
import java.util.Map; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import com.journaldev.spring.form.model.Employee; @Controller
public class EmployeeController { private static final Logger logger = LoggerFactory
.getLogger(EmployeeController.class); private Map<Integer, Employee> emps = null; @Autowired
@Qualifier("employeeValidator")
private Validator validator; @InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
} public EmployeeController() {
emps = new HashMap<Integer, Employee>();
} @ModelAttribute("employee")
public Employee createEmployeeModel() {
// ModelAttribute value should be same as used in the empSave.jsp
return new Employee();
} @RequestMapping(value = "/emp/save", method = RequestMethod.GET)
public String saveEmployeePage(Model model) {
logger.info("Returning empSave.jsp page");
return "empSave";
} @RequestMapping(value = "/emp/save.do", method = RequestMethod.POST)
public String saveEmployeeAction(
@ModelAttribute("employee") @Validated Employee employee,
BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
logger.info("Returning empSave.jsp page");
return "empSave";
}
logger.info("Returning empSaveSuccess.jsp page");
model.addAttribute("emp", employee);
emps.put(employee.getId(), employee);
return "empSaveSuccess";
}
}

  员工类代码:

 package com.journaldev.spring.form.model;

 public class Employee {

     private int id;
private String name;
private String role; public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
} }

  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 uri="http://www.springframework.org/tags/form"
prefix="springForm"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Employee Save Page</title>
<style>
.error {
color: #ff0000;
font-style: italic;
font-weight: bold;
}
</style>
</head>
<body> <springForm:form method="POST" commandName="employee"
action="save.do">
<table>
<tr>
<td>Employee ID:</td>
<td><springForm:input path="id" /></td>
<td><springForm:errors path="id" cssClass="error" /></td>
</tr>
<tr>
<td>Employee Name:</td>
<td><springForm:input path="name" /></td>
<td><springForm:errors path="name" cssClass="error" /></td>
</tr>
<tr>
<td>Employee Role:</td>
<td><springForm:select path="role">
<springForm:option value="" label="Select Role" />
<springForm:option value="ceo" label="CEO" />
<springForm:option value="developer" label="Developer" />
<springForm:option value="manager" label="Manager" />
</springForm:select></td>
<td><springForm:errors path="role" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Save"></td>
</tr>
</table> </springForm:form> </body>
</html>

spring 数据校验之Hibernate validation的更多相关文章

  1. 深入了解数据校验:Bean Validation 2.0(JSR380)

    每篇一句 > 吾皇一日不退役,尔等都是臣子 对Spring感兴趣可扫码加入wx群:`Java高工.架构师3群`(文末有二维码) 前言 前几篇文章在讲Spring的数据绑定的时候,多次提到过数据校 ...

  2. 深入了解数据校验:Java Bean Validation 2.0(JSR380)

    每篇一句 吾皇一日不退役,尔等都是臣子 相关阅读 [小家Java]深入了解数据校验(Bean Validation):基础类打点(ValidationProvider.ConstraintDescri ...

  3. 详述Spring对数据校验支持的核心API:SmartValidator

    每篇一句 要致富,先修路.要使用,先...基础是需要垒砌的,做技术切勿空中楼阁 相关阅读 [小家Java]深入了解数据校验:Java Bean Validation 2.0(JSR303.JSR349 ...

  4. Spring方法级别数据校验:@Validated + MethodValidationPostProcessor

    每篇一句 在<深度工作>中作者提出这么一个公式:高质量产出=时间*专注度.所以高质量的产出不是靠时间熬出来的,而是效率为王 相关阅读 [小家Java]深入了解数据校验:Java Bean ...

  5. 1. 不吹不擂,第一篇就能提升你对Bean Validation数据校验的认知

    乔丹是我听过的篮球之神,科比是我亲眼见过的篮球之神.本文已被 https://www.yourbatman.cn 收录,里面一并有Spring技术栈.MyBatis.JVM.中间件等小而美的专栏供以免 ...

  6. Hibernate数据校验简介

    我们在业务中经常会遇到参数校验问题,比如前端参数校验.Kafka消息参数校验等,如果业务逻辑比较复杂,各种实体比较多的时候,我们通过代码对这些数据一一校验,会出现大量的重复代码以及和主要业务无关的逻辑 ...

  7. 从深处去掌握数据校验@Valid的作用(级联校验)

    每篇一句 NBA里有两大笑话:一是科比没天赋,二是詹姆斯没技术 相关阅读 [小家Java]深入了解数据校验:Java Bean Validation 2.0(JSR303.JSR349.JSR380) ...

  8. 学习Spring Boot:(十)使用hibernate validation完成数据后端校验

    前言 后台数据的校验也是开发中比较注重的一点,用来校验数据的正确性,以免一些非法的数据破坏系统,或者进入数据库,造成数据污染,由于数据检验可能应用到很多层面,所以系统对数据校验要求比较严格且追求可变性 ...

  9. 用spring的@Validated注解和org.hibernate.validator.constraints.*的一些注解在后台完成数据校验

    这个demo主要是让spring的@Validated注解和hibernate支持JSR数据校验的一些注解结合起来,完成数据校验.这个demo用的是springboot. 首先domain对象Foo的 ...

随机推荐

  1. Java语法糖3:泛型

    泛型初探 在泛型(Generic type或Generics)出现之前,是这么写代码的: public static void main(String[] args) { List list = ne ...

  2. [.net 面向对象编程基础] (21) 委托

    [.net 面向对象编程基础] (20)  委托 上节在讲到LINQ的匿名方法中说到了委托,不过比较简单,没了解清楚没关系,这节中会详细说明委托. 1. 什么是委托? 学习委托,我想说,学会了就感觉简 ...

  3. Silverlight无法启动调试,错误“Unable to start debugging. The Silverlight Developer Runtime is not installed. Please install a matching version.” 解决办法

    今天调试Silverlight出现了以下错误: 意思是“无法启动调试,因为Silverlight Developer Runtime没有安装,请安装一个匹配的版本”.但是按Ctrl + F5可以调试运 ...

  4. AtomineerUtils爆破过程记录

    AtomineerUtils是国外的一款用于生成源代码注释的一款VS插件,官方网站:http://www.atomineerutils.com/products.php 通过链接,可以看出这款插件的功 ...

  5. js模版引擎handlebars.js实用教程——with-终极this应用

    返回目录 <!DOCTYPE html> <html> <head> <META http-equiv=Content-Type content=" ...

  6. 图文详解Unity3D中Material的Tiling和Offset是怎么回事

    图文详解Unity3D中Material的Tiling和Offset是怎么回事 Tiling和Offset概述 Tiling表示UV坐标的缩放倍数,Offset表示UV坐标的起始位置. 这样说当然是隔 ...

  7. CocoaPods 使用

    为什么要使用这个玩意呢,最近在使用swift开发项目,使用 swift 开源库的时候,在git上下载后居然不知道哪些是必须文件,还要思考下,看看哪些是需要的(不像原来oc开源库,一目了然),网上使用d ...

  8. js模仿新浪微博限制字数输入

    功能:实现新浪微博输入字数提醒功能:最多输入140个字,当输入字时,上面提示部分字数发生变化,如果字数小于25,字体颜色变红:当可输入字数为0时,强制不能输入,如果用中文输入法 一次性输入很多字,那么 ...

  9. Linux内核TCP/IP参数分析与调优

    转载于:http://www.itxuexiwang.com/a/liunxjishu/2016/0225/167.html?1456482565 如下图展示的是TCP的三个阶段.1,TCP三次握手. ...

  10. Time33算法

    Time33是字符串哈希函数,现在几乎所有流行的HashMap都采用了DJB Hash Function,俗称"Times33"算法.Times33的算法很简单,就是不断的乘33. ...