1.创建主页面
<form action="${pageContext.request.contextPath }/first.do" method="post">
<h1>数据验证</h1>
姓名:<input name="username"/>${nameErrormsg }<br/><br/>
成绩:<input name="score" />${scoreErrormsg }<br/><br/>
电话:<input name="phone" />${phoneErrormsg }<br/><br/>
<input type="submit" value="注册"/>
</form>
2.配置实体类
public class UserInfo {
@NotEmpty(message="用户名不能为空")
@Size(min=3,max=6,message="姓名长度应在{min}-{max}个字符")
private String username; @Min(value=0,message="成绩不能小于{value}")
@Max(value=100,message="成绩不能大于{value}")
private Integer score; @NotEmpty(message="手机号码不允许为空")
@Pattern(regexp="^1[34578]\\d{9}$",message="手机号码格式不正确")
private String phone; public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
} 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;
} }
3.配置控制器
@Controller
public class MyController {
// 处理器方法
@RequestMapping(value = "/first.do")
public ModelAndView doFirst(@Validated UserInfo info, BindingResult br) { ModelAndView mv = new ModelAndView();
mv.addObject("info", info);
mv.setViewName("/welcome.jsp"); int errorCount = br.getErrorCount(); if (errorCount > 0) { FieldError nameError = br.getFieldError("username");
FieldError scoreError = br.getFieldError("score");
FieldError phoneError = br.getFieldError("phone"); if (nameError != null) {
String nameErrormsg = nameError.getDefaultMessage();
mv.addObject("nameErrormsg", nameErrormsg);
}
if (scoreError != null) {
String scoreErrormsg = scoreError.getDefaultMessage();
mv.addObject("scoreErrormsg", scoreErrormsg);
}
if (phoneError != null) {
String phoneErrormsg = phoneError.getDefaultMessage();
mv.addObject("phoneErrormsg", phoneErrormsg);
} mv.setViewName("/index.jsp");
}
return mv;
} }
4.配置applicationContext.xml
<!-- 包扫描器 -->
<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注解驱动 -->
<mvc:annotation-driven validator="myValidator"/>
5.效果图