spring 数据校验之Hibernate validation
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的更多相关文章
- 深入了解数据校验:Bean Validation 2.0(JSR380)
每篇一句 > 吾皇一日不退役,尔等都是臣子 对Spring感兴趣可扫码加入wx群:`Java高工.架构师3群`(文末有二维码) 前言 前几篇文章在讲Spring的数据绑定的时候,多次提到过数据校 ...
- 深入了解数据校验:Java Bean Validation 2.0(JSR380)
每篇一句 吾皇一日不退役,尔等都是臣子 相关阅读 [小家Java]深入了解数据校验(Bean Validation):基础类打点(ValidationProvider.ConstraintDescri ...
- 详述Spring对数据校验支持的核心API:SmartValidator
每篇一句 要致富,先修路.要使用,先...基础是需要垒砌的,做技术切勿空中楼阁 相关阅读 [小家Java]深入了解数据校验:Java Bean Validation 2.0(JSR303.JSR349 ...
- Spring方法级别数据校验:@Validated + MethodValidationPostProcessor
每篇一句 在<深度工作>中作者提出这么一个公式:高质量产出=时间*专注度.所以高质量的产出不是靠时间熬出来的,而是效率为王 相关阅读 [小家Java]深入了解数据校验:Java Bean ...
- 1. 不吹不擂,第一篇就能提升你对Bean Validation数据校验的认知
乔丹是我听过的篮球之神,科比是我亲眼见过的篮球之神.本文已被 https://www.yourbatman.cn 收录,里面一并有Spring技术栈.MyBatis.JVM.中间件等小而美的专栏供以免 ...
- Hibernate数据校验简介
我们在业务中经常会遇到参数校验问题,比如前端参数校验.Kafka消息参数校验等,如果业务逻辑比较复杂,各种实体比较多的时候,我们通过代码对这些数据一一校验,会出现大量的重复代码以及和主要业务无关的逻辑 ...
- 从深处去掌握数据校验@Valid的作用(级联校验)
每篇一句 NBA里有两大笑话:一是科比没天赋,二是詹姆斯没技术 相关阅读 [小家Java]深入了解数据校验:Java Bean Validation 2.0(JSR303.JSR349.JSR380) ...
- 学习Spring Boot:(十)使用hibernate validation完成数据后端校验
前言 后台数据的校验也是开发中比较注重的一点,用来校验数据的正确性,以免一些非法的数据破坏系统,或者进入数据库,造成数据污染,由于数据检验可能应用到很多层面,所以系统对数据校验要求比较严格且追求可变性 ...
- 用spring的@Validated注解和org.hibernate.validator.constraints.*的一些注解在后台完成数据校验
这个demo主要是让spring的@Validated注解和hibernate支持JSR数据校验的一些注解结合起来,完成数据校验.这个demo用的是springboot. 首先domain对象Foo的 ...
随机推荐
- Entity Framework返回IEnumerable还是IQueryable?
在使用EF的过程中,我们常常使用repository模式,本文就在repository层的返回值是IEnumerable类型还是IQueryable进行探讨. 阅读目录: 一.什么是Repositor ...
- [Beautifulzzzz的博客目录] 快速索引点这儿O(∩_∩)O~~,红色标记的是不错的(⊙o⊙)哦~
3D相关开发 [direct-X] 1.direct-X最小框架 [OpenGL] 1.环境搭建及最小系统 [OpenGL] 2.企业版VC6.0自带的Win32-OpenGL工程浅析 51单片机 [ ...
- 简单JavaScript模版引擎优化
在上篇博客最简单的JavaScript模板引擎 说了一下一个最简单的JavaScript模版引擎的原理与实现,作出了一个简陋的版本,今天优化一下,使之能够胜任日常拼接html工作,先把上次写的模版函数 ...
- CSS折行小记
最近项目中遇到字段内容过长的显示问题. 后来在网上找了资料,http://www.php100.com/html/webkaifa/DIV_CSS/2009/0416/2453.html 用了td( ...
- Objective-C实现发短信和接电话
发短信: [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"sms://10000"]]; 打电话: ...
- redis配置文件redis.conf中文版(基于2.4)
转载于:http://www.itxuexiwang.com/a/shujukujishu/redis/2016/0216/99.html?1455869981 代码如下: # Redis示例配置文件 ...
- EF架构~CodeFirst模型下的数据初始化
回到目录 我为什么会来 在传统的大型系统设计中,数据库建模是个比开发更早的环节,先有数据库,然后是ORM模型,最后才是开发程序,而这种模型在EF出现后发生了转变,而且有可能将来会被code first ...
- windows下配置nginx+php环境
刚看到nginx这个词,我很好奇它的读法(engine x),我的直译是"引擎x",一般引"擎代"表了性能,而"x"大多出现是表示" ...
- H5常用代码:适配方案3
在H5项目中有一种常见的宣传页,就是那种整屏整屏的,带着炫丽进场动画的移动宣传页,不仅是一种欣赏也起到了很大宣传作用. 对于这种整屏的适配,前面通过视口的兼容处理也是可以做到的,但是在窄屏下会在上下有 ...
- C#学习系列-类与结构的区别
参考:http://www.microsoftvirtualacademy.com/Content/ViewContent.aspx?et=9851&m=9830&ct=31038 如 ...