概念
- 数据校验就是对数据的有效性进行验证
- 确保数据正确性,针对错误数据要有相应的处理方式
数据校验的两种方式
- 编程式数据校验 : 需要手动配置校验器
- 声明式数据校验(JSR-303规范)
编程式数据校验步骤
- 提供一个数据校验对象
- 编写数据校验器
- 进行数据校验
![](https://i-blog.csdnimg.cn/blog_migrate/39dfc9489ee4d40e944a0d777c5e6ba6.jpeg)
在编写代码之前,为了方便验证效果,简单应用一下国际化:
1、配置 xml 文件:
1、配置 xml 文件:
<!--国际化配置 格式和命名是标准的-->
<bean name="messageSource" class="org.springframework.context.support.ReloadableResourceBundl eMessageSource">
<!--指定messages属性文件的路径 -->
<property name="basename" value="classpath:/resource/messages"></property>
<property name="fileEncodings" value="utf-8"> </property>
</bean>
2、创建messages.properties属性文件,存放错误码对应的值 3、验证错误的 jsp 界面
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<body>
<form:form commandName="验证对象名,默认为对象 类名首字母小写">
<form:errors path="*"/>
</body>
代码演示
创建数据校验对象:
/**
* 用户数据模型
*
*/
public class UserModel {
//用户名
private String userName;
//密码
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/46fc92b252c469bb653c5341e3fc0d8c.jpeg)
编写数据校验器:
- 实现 Validator 接口并实现 supports()和 validate()
- supports 方法判断是否支持校验当前需要校验的对象,当 supports 方法返回 true 时,该 validate() 会被调用来对当前需要校验的实体类进行校验
/**
* 用户数据校验器
*
*/
public class UserValidater implements Validator{
//验证是否支持要校验的对象,此方法会在调用校验方法时自动先调用
@Override
public boolean supports(Class<?> clazz) {
return UserModel.class.equals(clazz);
}
//数据校验方法:在supports返回true后执行
//obj:表示校验器要校验的对象
//errors:假如校验对象有与我们规则不符的,不符的信息存放在errors中
@Override
public void validate(Object obj, Errors errors) {
//第一种校验方式:采用工具类
/*rejectIfEmpty中的参数:
field:字符串类型的field,实际上就是要校验的对象中的属性名,
errorCode:不用国际化可以直接写中文,提示错误信息,如果要国际化,就写错误提示码,不会直接显示,而是到国际化配置的属性文件中寻找对应的值,格式:实体对象名.属性名.规范
*/
ValidationUtils.rejectIfEmpty(errors, "userName", "user.username.notnull");
//第二种校验方式:采用针对参数对象的属性进行具体的规则制定
UserModel user = (UserModel) obj;
//密码不能为空
if(null != user && (null == user.getPassword() || "".equals(user.getPassword()))) {
errors.rejectValue("password", "user.password.notnull");
}
//用户名不能是管理员名
if("root".equals(user.getUserName()) || "admin".equals(user.getUserName())) {
errors.reject("user.username.forbidden");
}
}
}
进行数据校验:
/**
* 验证编程式数据校验器
*
*/
@Controller
@RequestMapping("/user")
public class UserController {
//引入自定义数据校验器
private UserValidater userValidater = new UserValidater();
@RequestMapping("/validate.do")
//处理请求的方法
//参数:errors:用于绑定错误信息
public String validateUser(UserModel user,Errors errors) {
//对获取的参数进行校验
userValidater.validate(user, errors);
//判断是否通过了数据校验
if(errors.hasErrors()) {
//如果有错误信息,那么返回到错误页面
return "error";
}
return "success";
}
}
声明式数据校验步骤
- 在原有包基础上导入包:
-
配置文件引入: - 提供校验对象
- 进行数据校验
在编写代码之前,声明式数据校验读取自定义的国际化资源文件:
<bean name="validator" class=
"org.springframework.validation.beanvalidation.LocalValidatorFactoryBean ">
<!--生产者类:提供校验功能的类 -->
<property name="providerClass" value=" org.hibernate.validator.HibernateValidator"></property>
<!--指定错误消息资源文件(如果不指定,默认使用classpath:路径去找validationMessageSource.properties) -->
<property name="validationMessageSource" ref="messageSource"></property>
</bean>
代码演示
提供校验对象:
/**
* 学生数据模型
*
*/
public class StudentModel {
/*
* 声明式数据校验在遵循默认的国际化配置时,会把message中的内容当做错误码去messages属性文件中查找到对应的值,如果查找不到,那么就会显示错误码
*/
//@NotNull(message="学生姓名不能为空") //message的值是不符合规则以后的错误信息
@NotNull(message="{student.studentname.notnull}")
private String studentName;
@Email(message="邮箱地址不正确")
private String email;
@Length(min=5,max=20,message="地址长度不正确")
private String address;
@Min(value=18,message="年龄未满18岁")
private Integer age;
//省略getter、setter方法
进行数据校验:
/** * 演示声明式数据校验 * */
@Controller
@RequestMapping
(
"/student"
)
public
class
StudentController
{
//处理请求方法
@RequestMapping
(
"/validate.do"
)
//在此处的modelattribute的值,即为jsp页面中的commandName的值
public
String
validateStu
(
@Valid
@ModelAttribute
(
"stu"
)
StudentModel
student
,
Errors
errors
)
{
if
(
errors
.
hasErrors
())
{
return
"stError"
;
}
return
"success"
;
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/4fb06eb9b0d1cc795244e0b2bfd8406e.jpeg)
![](https://i-blog.csdnimg.cn/blog_migrate/a7ac265f2d5ddd1fa53570f62aa60ed2.jpeg)
![](https://i-blog.csdnimg.cn/blog_migrate/cc8c5f556d99fb5558267dd0d2f96a43.jpeg)
![](https://i-blog.csdnimg.cn/blog_migrate/f201bf946cea94a52b4600a4bb48708f.jpeg)
![](https://i-blog.csdnimg.cn/blog_migrate/c1e3c415653c07c8a986663ec35b13c9.jpeg)
![](https://i-blog.csdnimg.cn/blog_migrate/ed998fe8a8022c5f701cf974e1851b55.jpeg)