步骤一:引入四个jar包
步骤二:注册类型转换器
<context:component-scan base-package="cn.happy.controller"></context:component-scan> <!-- 配置验证器 --> <bean id="myvalidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property> </bean> <mvc:annotation-driven validator="myvalidator"/>
步骤三:为实体类进行注解约束
package cn.happy.entity; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.NotEmpty; /** * @Min最小值 * @Max最大值 * @NotEmpty 不允许为空 * @Pattern 使用正则校验 * @Size 长度 */ public class UserInfo { //必须是0到100之间 @Min(value=0,message="成绩最小值为{value}") @Max(value=100,message="成绩最大值为{value}") @NotEmpty(message="成绩不允许为空") private Integer score; //手机号码必须不能为空,必须是以1 开头 第二位3,4,5,6,7,8,9 最后9位随意 @NotEmpty(message="手机号码不允许为空") @Pattern(regexp="^1[3,4,5,6,7,8,9]\\d{9}$",message="手机号码不正确") private String phone; //不能为空 //必须是6个字符以上 @NotEmpty(message="用户名不能为空") @Size(min=6,message="名称至少6个字符") private String name; public Integer getScore() { return score; } public void setScore(Integer score) { this.score = score; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
步骤四:编写Handler控制器
package cn.happy.controller; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import cn.happy.entity.UserInfo; @Controller public class FirstController { @RequestMapping("/first.do") public ModelAndView doFirst(@Valid UserInfo info,BindingResult br){ ModelAndView mv=new ModelAndView(); mv.setViewName("/WELCOME.jsp"); //记录到底是哪个字段验证失败了 //有一个可以侦测到验证错误总数的方法 int errorCount = br.getErrorCount(); if (errorCount>0) { //证明模型验证失败 FieldError score = br.getFieldError("score"); FieldError name = br.getFieldError("name"); FieldError phone = br.getFieldError("phone"); if (score!=null) { mv.addObject("scoremsg",score.getDefaultMessage()); } if (name!=null) { mv.addObject("namemsg",name.getDefaultMessage()); } if (phone!=null) { mv.addObject("phonemsg",phone.getDefaultMessage()); } mv.setViewName("/index.jsp"); } //高中 英文版的吻别 return mv ; } }