spring自带一些数据验证,同时可以配合使用JSR 303 方式,加入bean-validator.jar包即可。
如下:
package cn.edu.bjut.model;
import java.util.Date;
import java.util.Random;
import javax.validation.constraints.Past;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;
public class Emplyee {
private String id;
public Emplyee(){
int id_value = new Random().nextInt();
id = id_value >= 0?id_value+"":-id_value+"";
}
@NotEmpty
private String name;
@NumberFormat
private Integer age;
@DateTimeFormat(pattern="yyyy-MM-dd")
@Past
private Date birthday;
@Email
private String email;
private String department;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
@Override
public String toString() {
return "Emplyee [id=" + id + ", name=" + name + ", age=" + age
+ ", birthday=" + birthday + ", email=" + email
+ ", department=" + department + "]";
}
}
在controller里面的add方法和update方法中的bean类型参数前加上@Validated,同时紧跟着BingingResult br,通过判断br.hasErrors()返回的boolean值来判断是否能够提交。
在前台jsp上要通过SpringMVC的表单标签在表单提交失败时显示错误信息,如<form:errors path="name"/>。
错误信息的配置是利用国际化资源信息的方式,在classpath下面新建i18n.properties,新建错误提示信息,如
NotEmpty.emplyee.name=name\u4E0D\u80FD\u4E3A\u7A7A //name不能为空
typeMismatch.emplyee.birthday=\u8F93\u5165\u7684\u4E0D\u662F\u4E00\u4E2A\u65E5\u671F //非日期格式信息
Email.emplyee.email=\u90AE\u7BB1\u683C\u5F0F\u4E0D\u89C4\u8303 //邮箱格式错误
Past.emplyee.birthday=\u751F\u65E5\u5E94\u8BE5\u4E3A\u4E4B\u524D\u7684\u65E5\u671F //非过去时期
typeMismatch.emplyee.age=\u5C81\u6570\u8981\u4E3A\u6574\u6570 //不是整数类型
注意key值的写法,通常是@信息.bean.属性;typeMismatch是用来指定格式不对应情况,写完上述还得在SpringMVC配置文件里面加上MessageSource的配置
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource" >
<property name="basename" value="i18n"/>
</bean>
这样,即可