maven依赖:http://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator/6.0.10.Final
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.10.Final</version>
</dependency>
配置验证器:
<!-- 配置验证器 -->
<bean id="myvalidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
</bean>
<mvc:annotation-driven validator="myvalidator"/>
UserInfo类
package entity;
import javax.validation.constraints.*;
public class UserInfo {
//成绩
@NotNull //不能为空
@Min(value=0,message="成绩最小值为{value}") //最小值
@Max(value=100,message="成绩最大值为{value}") //最大值
private Integer score;
//姓名
@NotNull
@Size(min=6,message="名称至少6个字符") //字符
private String name;
//成绩
@NotNull
@Pattern(regexp="^1[3,4,5,6,7,8,9]\\d{9}$",message="手机号码格式不正确")
private String phone;
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
Controller类:
@RequestMapping("/vali")
public ModelAndView vali(@Valid UserInfo userInfo, BindingResult br){
ModelAndView mv=new ModelAndView();
mv.setViewName("welcome");
int count = br.getErrorCount();
if(count>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");
}
return mv;
}
index.jsp
<form action="vali" method="post">
成绩:<input name="score" /> <span>${scoremsg }</span><br/><br/>
姓名:<input name="name"/><span>${namemsg }</span><br/><br/>
电话:<input name="phone"/><span>${phonemsg }</span><br/><br/>
<input type="submit" value="提交"/>
</form>