Spring(十五)数据校验
数据校验简单来说就是判断你输入的是否合法,比如用户名不能为空
1.首先创建一个UserInfo类
public class UserInfo { @NotNull(message = "用户名不能为空") @Size(min = 6,max = 20,message = "用户名必须在{min}-{max}之间") private String name; @Max(value = 150,message = "年龄不能超过150岁") @Min(value = 10,message = "年龄最小不能小于10岁") private Integer age; @DateTimeFormat(style = "yyyy-MM-dd") private Date birthday; @NotNull(message = "手机不能为空") @Pattern(regexp = "1[35789]\\d{9}",message = "手机格式不正确") private String phone; @NotNull(message = "邮箱不能为空")//wfewf@qq.com @Pattern(regexp = "^\\w+@\\w+\\.\\w+$",message = "邮箱格式不正确") private String email; 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 getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
2.创建一个类:
@Controller public class FirstController { @RequestMapping("/first") public String doFirst(@Valid UserInfo info, BindingResult br, Model model){ if(br.getErrorCount()>0){ FieldError name = br.getFieldError("name"); FieldError age = br.getFieldError("age"); FieldError birthday = br.getFieldError("birthday"); FieldError email = br.getFieldError("email"); FieldError phone = br.getFieldError("phone"); if (name!=null){ String namemsg=name.getDefaultMessage(); model.addAttribute("namemsg",namemsg); model.addAttribute("namevalue",info.getName()); } if (age!=null){ String agemsg=age.getDefaultMessage(); model.addAttribute("agemsg",agemsg); } if (birthday!=null){ String birthdaymsg=birthday.getDefaultMessage(); model.addAttribute("birthdaymsg",birthdaymsg); } if (email!=null){ String emailmsg=email.getDefaultMessage(); model.addAttribute("emailmsg",emailmsg); } if (phone!=null){ String phonemsg=phone.getDefaultMessage(); model.addAttribute("phonemsg",phonemsg); } return "validator"; } return "success"; } }
3.配置文件:
4.jsp注册页面: