码迷,mamicode.com
首页 > 其他好文 > 详细

数据校验

时间:2017-09-04 13:26:44      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:ror   provider   err   坚持   count   bin   reg   ber   mvc   

学习这条路没有捷径可走。愿我们一直坚持不懈的走下去,初心不忘!

数据校验 也叫 数据验证

比较常用的 Hibernate validater

1.引jar包  4个

 

<!--数据验证-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.0.1.GA</version>
</dependency>

<!--jboss logging-->
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.3.0.Final</version>
</dependency>

<!--validation api-->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>

<!--slf4j api 日志接口-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
2.配置验证器
<!-- 验证器 -->
<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"></mvc:annotation-driven>

3在Model上打标记
public class UserInfo {
//需是0~100之间
@Min(value = 0,message = "成绩最小值为{value}")
@Max(value = 100,message = "成绩最大值为{value}")
private Integer score;

@NotEmpty(message = "用户不能为空")
@Size(min = 4,message = "名称至少4个")
private String name;

@NotEmpty(message = "手机号不能为空")
@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;
}
}

4 在Controller方法中
植入二个参数


@Controller
public class FirstController {
@RequestMapping("/first")
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;

}
}

 

 







 

数据校验

标签:ror   provider   err   坚持   count   bin   reg   ber   mvc   

原文地址:http://www.cnblogs.com/wangdan123/p/7472940.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!