SpringMVC(十六)數據校驗
阿新 • • 發佈:2018-04-01
解析器 demo1 color != span 錯誤 一個用戶 gem ted
一、什麽是數據校驗?
這個比較好理解,就是用來驗證客戶輸入的數據是否合法,比如客戶登錄時,用戶名不能為空,或者不能超出指定長度等要求,這就叫做數據校驗。
數據校驗分為客戶端校驗和服務端校驗
客戶端校驗: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>
SpringMVC(十六)數據校驗