1.引入jar包java
2.配置驗證器web
<!-- 配置驗證器 -->
<bean id="myvalidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
</bean>
<mvc:annotation-driven validator="myvalidator"/>
3.建立實體spring
package cn.happy.entity; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.NotEmpty; import org.jboss.logging.Message; public class UserInfo { //必須是0到100之間 @NotNull(message="成績不能爲空") @Min(value=0,message="成績最小值爲{value}") @Max(value=100,message="成績最大值爲{value}") 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; } }
4.編寫handlermvc
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 ; } }