<mvc:annotation-driven />
<bean id="validatorFactoryBean" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
<mvc:annotation-driven validator="validatorFactoryBean"/>
@Null / @NotNull | 被注解的元素必须为null / 必须不为null |
@AssertTrue / @AssertFalse | 被注解的元素必须为true / 必须为false |
@Min(value) / @Max(value) | 被注解的元素必须大于等于指定最小值 / 小于等于指定最大值 |
@DecimalMin(value) / @DecimalMax(value) | 同上,同时被注解元素必须为一个数字 |
@Size(max,min) | 被注解的元素必须在指定范围内 |
@Digits(integer,fraction) | 同上,被注解的元素必须是一个数字 |
@Past / @Future | 被注解的元素必须是一个过去的时间 / 必须是一个将来的时间 |
被注解的元素必须是一个Email格式 | |
@Pattern(regexp) | 被注解的元素必须通过正则表达式regexp的验证,该元素必须是一个String |
@NotEmpty | 被注解的元素必须不为空 |
@Length(min,max) | 被注解的元素长度必须在指定范围内,一般为 String 类型 |
@Range | 被注解的元素必须在核实范围内; |
package site.assad.domain;
import org.springframework.format.annotation.DateTimeFormat;
import javax.validation.constraints.*;
public class User {
private int userId;
message="用户名不可为空") (
regexp = "\\S{2,15}",message="用户名必须包含2-15个非空字符") (
private String userName;
message="用户密码不可为空") (
regexp = "\\w{6,30}",message="密码必须包含6-30个有字符,下划线,数字组成的字符") (
private String password;
message="邮箱格式错误") (
private String email;
message="必须是一个过去的日期") (
pattern = "yyyy-MM-dd") //数据格式化 (
private Date birthday;
//省略getter,setter
}
FieldError getFieldError(String field) | 根据属性名获取对应的校验错误 |
List |
获取所有的校验错误 |
Object getFieldValue(String field) | 获取属性值 |
int getErrorCount() | 获取错误数量 |
boolean hasError() | 判断是否含有校验错误 |
//响应 “/register”请求,将数据绑定到“user”模型后,进行数据校验,将校验结果绑定到 BindingResult对象中
"/handleRegister") (
public String register( ("user") User user,BindingResult bindingResult){
if(bindingResult.hasErrors())
return "/user/register";
else
return "/user/showDetail";
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>用户注册title>
<style> .error{color:darkred;} style>
head>
<body>
<jsp:useBean id="user" class="site.assad.domain.User" scope="request" />
<form:form action="/user/handleRegister" method="post" modelAttribute="user">
用户名:<form:input path="userName" /><br/>
<form:errors path="userName" cssClass="error"/><br />
密码:<form:input path="password" /><br/>
<form:errors path="password"/><br />
Email:<form:input path="email" cssClass="error" /><br/>
<form:errors path="email"/><br />
生日(格式"yyyy-MM-dd"):<form:input path="birthday" /><br/>
<form:errors path="birthday" cssClass="error"/><br />
<input type="submit" value="提交" />
<input type="reset" value="重置" /><br/>
form:form>
body>
html>
#标准验证标签信息
register.userName.notNull=用户名必须不为空
register.userName.pattern=用户名必须包含2-15个非空字符
register.password.pattern=密码必须包含6-30个有字符,下划线,数字组成的字符
register.email=邮箱格式错误
register.birthday.past=必须是一个过去的日期
<beans ....>
...
...
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"
p:defaultEncoding="UTF-8"
p:basename="i18n/message"/>
<bean id="validatorFactoryBean" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"
p:validationMessageSource-ref="messageSource" />
<mvc:annotation-driven validator="validatorFactoryBean"/>
beans>
public class User {
private int userId;
message="{register.userName.notNull}") (
regexp = "\\S{2,15}",message="{register.userName.pattern}") (
private String userName;
regexp = "\\w{6,30}",message="{register.password.pattern}") (
private String password;
message="{register.email}") (
private String email;
message="{register.birthday.past}") (
pattern = "yyyy-MM-dd") (
private Date birthday;
//省略 getter,setter
}
BindingResult#rejectValue(String field,String errorCode); //向BindingResult对象注入值
ValidationUtils.rejectIfEmptyOrWhitespace(BindingResult bindingResult,String field,String errorCode) //通过校验器工具向 Bindingresult 注入值,同时提供了空值检验的便捷方法
package site.assad.web;
"/user") (
public class UserController {
private UserService userService;
//只负责路由转换
"/register") (
public String register(){
return "/user/jsp/register";
}
//相应表单提交页面的路由请求,进行数据校验;
value="/handleRegister",method=RequestMethod.POST) (
public String register1( ("user") User user, BindingResult bindingResult,Model model){
if(bindingResult.hasErrors()){
return "/user/jsp/register";
}
boolean flag = userService.registerUser(user);
if(flag){
user = userService.getUserByName(user.getUserName());
model.addAttribute("user",user);
return "/user/jsp/userDetail";
}else{
//当userName在数据库中已经存在,返回注册页面,同时向 BindingResult 注入“userName”的校验失败信息
bindingResult.rejectValue("userName","repeated");
return "/user/jsp/register";
}
}
}
#自定义验证信息
repeated.userName=用户名已经存在
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"
p:defaultEncoding="UTF-8"
p:basename="i18n/message"/>
<mvc:annotation-driven />
package site.assad.web.validator;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
//针对 User 的校验器
public class UserValidator implements Validator {
private UserService userService;
//判断需要需要校验的类
public boolean supports(Class> clazz) {
return User.class.equals(clazz);
}
//校验逻辑
public void validate(Object target, Errors errors) {
if (target instanceof User) {
User user = (User) target;
if (userService.getUserByName(user).getUserId != 0) {
errors.rejectValue("userName", "repeated"); //向错误对象中写入i18n资源中对应的错误码,同上
}
}
}
}
public class UserController{
public void initBinder(WebDataBinder binder){
binder.setValidator(new UserValidator()); //在进行数据绑定是使用自定义校验器
}
"/handleRegister") (
public String register( ("user") User user,BindingResult bindingResult,Model model){
if(bindingResult.hasErrors()){
return "/user/register";
}else{
user = userService.getUserByName(user.getUserName());
model.addAttribute("user",user);
return "/user/showDetail";
}
}
}
<bean id="userValidator" class="site.assad.validator.UserValidator"/>
<mvc:annotation-driven validator="userValidator"/>