引入相应的jar包
<!-- start springMVC表单验证 -->
<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>
<!-- end springMVC表单验证 -->
验证Model对象
public class ValidatorBean {
/**
* 登录用户名
*/
// message 直接提供错误信息
@NotNull(message = "username 不能为空")
// message 使用 {} 代表错误内容,从 resources 目录下的 ValidationMessages.properties文件中读取
@Pattern(regexp = "[a-zA-Z0-9_]{5,10}", message = "{user.username.illegal}")
private String username;
/**
* 登录密码
*/
// ValidationMessages.properties文件中读取
@Size(min = 5, max = 10, message = "{password.length.illegal}")
private String password;
/**
* 用户姓名
*/
@Size(min = 2, max = 30, message = "用户名长度必须大小{min},小于{max}位")
@NotNull(message = "用户名不能为空")
private String firstName;
/**
* 日期验证
*/
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Past(message = "生日日期必须早于当前日期") // 验证注解的元素值(日期类型)比当前时间早
private Date brithDay;
@AssertFalse(message = "参数值必须为false")
private Boolean isFalse;
@AssertTrue(message = "参数值必须为true")
private Boolean isTrue;
@Email(message = "email格式不正确")
private String email;
@Length(min = 4, max = 20, message = "部门名称长度必须大于{min},小于{max}")
@NotBlank(message = "部门名称不能为空,去掉首尾空格")
private String section;
@Range(min = 18, max = 60, message = "年龄必须大于{min},小于{max}")
private int age;
@Null(message = "参数值必须为null值")
private String strNull;
@NotNull(message = "参数值不能为null值")
private String strNotNull;
@Max(value = 20, message = "值必须大于等于{value}")
private int intMax;
@Min(value = 8, message = "值必须大于等于{value}")
private int intMin;
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Future(message = "未来日期必须大于当前日期")
private Date futureDate;
@Digits(integer = 5, fraction = 2, message = "Float整数最多{integer}位,小于最多{fraction}位")
private Float floatValue;
@DecimalMax(value = "100", message = "Long的值必须小于{value}")
private long longMax;
@DecimalMin(value = "1", message = "Long的值必须大于{value}")
private long longMin;
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;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Date getBrithDay() {
return brithDay;
}
public void setBrithDay(Date brithDay) {
this.brithDay = brithDay;
}
public Boolean getIsFalse() {
return isFalse;
}
public void setIsFalse(Boolean isFalse) {
this.isFalse = isFalse;
}
public Boolean getIsTrue() {
return isTrue;
}
public void setIsTrue(Boolean isTrue) {
this.isTrue = isTrue;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getStrNull() {
return strNull;
}
public void setStrNull(String strNull) {
this.strNull = strNull;
}
public String getStrNotNull() {
return strNotNull;
}
public void setStrNotNull(String strNotNull) {
this.strNotNull = strNotNull;
}
public int getIntMax() {
return intMax;
}
public void setIntMax(int intMax) {
this.intMax = intMax;
}
public int getIntMin() {
return intMin;
}
public void setIntMin(int intMin) {
this.intMin = intMin;
}
public Date getFutureDate() {
return futureDate;
}
public void setFutureDate(Date futureDate) {
this.futureDate = futureDate;
}
public Float getFloatValue() {
return floatValue;
}
public void setFloatValue(Float floatValue) {
this.floatValue = floatValue;
}
public long getLongMax() {
return longMax;
}
public void setLongMax(long longMax) {
this.longMax = longMax;
}
public long getLongMin() {
return longMin;
}
public void setLongMin(long longMin) {
this.longMin = longMin;
}
}
验证消息提示文件
ValidationMessages.properties
user.username.illegal=用户名格式不正确
password.length.illegal=密码[${validatedValue}]长度必须为{min}到{max}个字符
暂时没有走通如何配置提示消息的国际化配置
Controller代码
@Controller
@RequestMapping("/home")
public class ValidateStudentController {
/**
* 表单提交方法
*/
@RequestMapping(value="/index", method = {RequestMethod.GET})
public String index(Model model){
//如果模型数据中包含同名数据则不再添加,
//如果不判断将一直重新new新的模型数据
if(!model.containsAttribute("validatorBean")){
ValidatorBean validatorBean = new ValidatorBean();
model.addAttribute("validatorBean", new ValidatorBean());
}
return "springmvc/student/index";
}
/**
* 表单验证方法
*/
@RequestMapping(value="/index", method = {RequestMethod.POST})
public String indexSave(Model model, @Valid @ModelAttribute("validatorBean") ValidatorBean validatorBean,
BindingResult result) throws UnsupportedEncodingException{
//如果存在验证错误信息重定向到表单提交展示错误信息
if(result.hasErrors()){
return index(model);
}
return "redirect:success";
}
/**
* 表单提交验证成功方法
*/
@RequestMapping(value="/success")
public String success(Model model){
return "springmvc/student/success";
}
}
jsp代码
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Java验证框架测试</title>
</head>
<body>
<form:form modelAttribute="validatorBean" method="post">
登录用户名:<form:input path="username" /><br/>
<span style="color: red;"><form:errors path="username" /></span><br/>
登录密码: <form:input path="password" /><br/>
<span style="color: red;"><form:errors path="password" /></span><br/>
用户姓名: <form:input path="firstName" /><br/>
<span style="color: red;"><form:errors path="firstName" /></span><br/>
出生日期: <form:input path="brithDay" /><br/>
<span style="color: red;"><form:errors path="brithDay" /></span><br/>
必须是False: <form:input path="isFalse" /><br/>
<span style="color: red;"><form:errors path="isFalse" /></span><br/>
必须是True: <form:input path="isTrue" /><br/>
<span style="color: red;"><form:errors path="isTrue" /></span><br/>
Email: <form:input path="email" /><br/>
<span style="color: red;"><form:errors path="email" /></span><br/>
部门名称: <form:input path="section" /><br/>
<span style="color: red;"><form:errors path="section" /></span><br/>
年龄: <form:input path="age" /><br/>
<span style="color: red;"><form:errors path="age" /></span><br/>
最大值: <form:input path="intMax" /><br/>
<span style="color: red;"><form:errors path="intMax" /></span><br/>
最小值: <form:input path="intMin" /><br/>
<span style="color: red;"><form:errors path="intMin" /></span><br/>
未来日期: <form:input path="futureDate" /><br/>
<span style="color: red;"><form:errors path="futureDate" /></span><br/>
整数小数位验证: <form:input path="floatValue" /><br/>
<span style="color: red;"><form:errors path="floatValue" /></span><br/>
最大值: <form:input path="longMax" /><br/>
<span style="color: red;"><form:errors path="longMax" /></span><br/>
最小值: <form:input path="longMin" /><br/>
<span style="color: red;"><form:errors path="longMin" /></span><br/>
必须为null值: <form:input path="strNull" /><br/>
<span style="color: red;"><form:errors path="strNull" /></span><br/>
必须不为null值: <form:input path="strNotNull" /><br/>
<span style="color: red;"><form:errors path="strNotNull" /></span><br/>
<input type="submit" value="提交"/>
</form:form>
</body>
</html>
运行效果
注意事项:
1、消息提示文件中的汉字需要使用unicode码,否则会显示乱码。
待完善功能:
1、验证提示消息的国际化读取、验证文件的位置配置
2、多个数据模型在同一个表单中进行数据验证