一、什么是数据校验?
这个比较好理解,就是用来验证客户输入的数据是否合法,比如客户登录时,用户名不能为空,或者不能超出指定长度等要求,这就叫做数据校验。
数据校验分为客户端校验和服务端校验
客户端校验:js校验
服务端校验:springmvc使用validation校验,struts2使用validation校验。都有自己的一套校验规则。
数据校验
第一步:引入依赖
<!--数据校验--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.3.1.Final</version> </dependency> <!--validation api--> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.0.0.GA</version> </dependency>
第二步:配置验证器在springmvc.xml中
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="demo18Validator"></context:component-scan> <!--视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--配置验证器--> <bean id="myValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property> </bean> <!--注解驱动--> <mvc:annotation-driven validator="myValidator"></mvc:annotation-driven> </beans>
第三步:使用注解驱动关联验证器
在这里要声明一个用户类
package demo18Validator.domain; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.format.annotation.DateTimeFormat; import javax.validation.constraints.*; import java.util.Date; /** * Created by mycom on 2018/3/31. */ public class UserInfo { @NotEmpty(message = "用户名不能为空") @Size(min = 6,max = 20,message = "用户名必须在{min}-{max}之间") private String username; @Max(value = 150,message = "年龄最大不能超过150") @Min(value=18,message = "年龄做小不能低于18") private Integer userage; @NotNull(message = "出生日期不能为空") @DateTimeFormat(pattern = "yyyy-MM-dd") private Date birthday; @NotEmpty(message = "手机号码不能为空") @Pattern(regexp = "^1[3|5|7|8|9]\\d{9}$",message = "手机号格式不正确") private String userphone; @NotEmpty(message = "邮箱不能为空") @Pattern(regexp = "^\\w+@\\w+\\.\\w+$",message = "邮箱格式不正确") private String email; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Integer getUserage() { return userage; } public void setUserage(Integer userage) { this.userage = userage; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getUserphone() { return userphone; } public void setUserphone(String userphone) { this.userphone = userphone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
第四步:写控制器类
package demo18Validator; import demo18Validator.domain.UserInfo; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.RequestMapping; import javax.validation.Valid; /** * Created by mycom on 2018/3/31. */ @Controller public class FirstController { @RequestMapping("/first") public String doFirst(@Valid UserInfo info, BindingResult br, Model model){ //判断br中错误总数是否大于0,如果大于0那么在模型中至少有一个是验证错误的 if(br.getErrorCount()>0){ //模型验证失败,获取到那个属性验证失败了 FieldError username = br.getFieldError("username"); FieldError userage = br.getFieldError("userage"); FieldError userphone = br.getFieldError("userphone"); FieldError email = br.getFieldError("email"); FieldError birthday = br.getFieldError("birthday"); //如果usernamemsg不为空那么就是他验证失败,同理其他属性也是 if(username!=null){ //验证失败后,获得到失败的信息,并把它放入model中 String usernamemsg = username.getDefaultMessage(); model.addAttribute("usernamemsg",usernamemsg); } if(userage!=null){ //验证失败后,获得到失败的信息,并把它放入model中 String useragemsg = userage.getDefaultMessage(); model.addAttribute("useragemsg",useragemsg); } if(userphone!=null){ //验证失败后,获得到失败的信息,并把它放入model中 String userphonemsg = userphone.getDefaultMessage(); model.addAttribute("userphonemsg",userphonemsg); } if(email!=null){ //验证失败后,获得到失败的信息,并把它放入model中 String emailmsg = email.getDefaultMessage(); model.addAttribute("emailmsg",emailmsg); } if(birthday!=null){ //验证失败后,获得到失败的信息,并把它放入model中 String birthdaymsg = birthday.getDefaultMessage(); model.addAttribute("birthdaymsg",birthdaymsg); } /*验证失败后,仍然会到表单页面*/ return "validator"; } /*验证成功之后跳到成功页面*/ return "success"; } }
页面上
<%-- Created by IntelliJ IDEA. User: mycom Date: 2018/3/31 Time: 17:19 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> <h1>数据校验</h1> <form action="${pageContext.request.contextPath}/first" method="post"> 年龄:<input name="userage" /> <span>${useragemsg }</span><br/><br/> 姓名:<input name="username"/><span>${usernamemsg }</span><br/><br/> 电话:<input name="userphone"/><span>${userphonemsg }</span><br/><br/> 出生日期:<input name="birthday"/> <span>${birthdaymsg}</span><br/><br/> 邮箱:<input name="email"/> <span>${emailmsg}</span><br/><br/> <input type="submit" value="注册"/> </form> </body> </html>
成功页面
<%-- Created by IntelliJ IDEA. User: mycom Date: 2018/3/26 Time: 11:57 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> 登录成功! </body> </html>