initBinder进行数据校验
这样的验证可以指比对birthday这一项
填写完form表单后,进入此方法,便可进行出生日期的后台数据校验
xml文件同样
没有太多,主要是注解
二继承
此类
public class MyDateEditor extends PropertiesEditor { @Override //从网线打过来一个长得像日期的字符串 我,哦们 需要的是Date public void setAsText(String str) throws IllegalArgumentException { SimpleDateFormat sdf=getDate(str); Date date = null; try { date = sdf.parse(str); } catch (ParseException e) { e.printStackTrace(); } setValue(date); } public SimpleDateFormat getDate(String str) { SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日"); //yyyy-MM-dd if (Pattern.matches("^\\d{4}-\\d{1,2}-\\d{2}$",str)){ sdf=new SimpleDateFormat("yyyy-MM-dd"); } if (Pattern.matches("^\\d{4}/\\d{1,2}/\\d{2}$",str)){ sdf=new SimpleDateFormat("yyyy/MM/dd"); } if (Pattern.matches("^\\d{4}\\d{1,2}\\d{2}$",str)){ sdf=new SimpleDateFormat("yyyyMMdd"); } return sdf; } }
这一种是继承propertiesEditor类即可
在建立实体类是我们就可以添加注解来进行数据校验
不过在此之前添加jar包
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.1.Final</version>
</dependency>
<!--validation api-->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
一个是hibernate,一个是validation
创建实体类
public class UserInfo { @NotEmpty(message = "用户名不能为空") @Size(min = 2,max = 10,message = "用户名的长度必须在{min}-{max}之间") private String username; @Max(value = 100,message = "最老100岁") @Min(value = 18,message = "最小18岁") private Integer userage; @NotNull(message = "出生日期不能为空") @DateTimeFormat(pattern = "yyyy/MM/dd") private Date birthday; @NotEmpty(message = "手机不能为空") @Pattern(regexp = "^1[3|5|7|9|8]\\d{9}$",message = "手机号码格式不正确") private String userphone; @NotEmpty(message = "邮箱不能为空") //yymqqc@126.com @Pattern(regexp = "^\\w+@\\w+\\.\\w+$",message = "邮箱格式不正确") private String email; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Integer getUserage() { return userage; } public void setUserage(Integer userage) { this.userage = userage; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getUserphone() { return userphone; } public void setUserphone(String userphone) { this.userphone = userphone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
嗯,就是如此,以及xml配置文件的内容