數據驗證及文件操做

數據驗證及文件操做前端

1、數據驗證

  在開發中,凡有表單提交的地方,就必須作數據的驗證,數據驗證必須在兩個地方都要作,一個是前端驗證,一個服務端再次驗證。git

前端的驗證都是用JS腳原本實現,由於js是運行在客戶端,執行速度快,不須要服務器參與,減小服務端壓力,用戶體驗好。可是,瀏覽器是能夠禁用js腳本運行,因此就能夠繞過客戶端驗證,直接把錯誤數據提交到服務端,因此必須在服務端再次驗證。正則表達式

後端驗證的方式是寫Java代碼來實現驗證, 以下:spring

// 增,數據庫

@RequestMapping(value = "save")後端

public ModelAndView save(Student student) {瀏覽器

 if(student.getName().length()== 0) {服務器

        

 }else if (student.getPhone().length()!=11) {app

        

 }框架

return new ModelAndView("studentList");

}

 

 

驗證框架的使用步驟:

  1. 導入驗證框架的jar

 

 

  1. springMVC的配置文件配置驗證框架,在提交時,SpringMVC在封裝數據時,啓動驗證框架對數據進行驗證。

 

<!-- 校驗器 -->

<bean class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">

   <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>

   <property name="validationMessageSource" ref="validationMessageSource"/>

</bean>

<!-- 驗證消息器 --> 

<bean id="validationMessageSource"   class="org.springframework.context.support.ReloadableResourceBundleMessageSource"/>

 

  1. 在要封裝的實體對象的屬性前或屬性的set方法前添加相應的驗證規則(註解),注意,驗證框架只是驗證有沒有錯誤,它不會對錯誤進行片。

@Length(min=6,max=10,message="姓名的長度是6-10個字符!")

@NotBlank(message="姓名不能爲空!")

private String name;

private String sex;

@Range(min=18,max=40,message="年齡在18-40歲之間!")

private int age;

@NotBlank(message="電話不能爲空!")

@Pattern(regexp="^1[3|4|5|7|8][0-9]{9}$",message="手機號碼不正確!")

private String phone;

@NotBlank(message="地址不能爲空!")

private String address;

@Email(message="郵箱格式不正確!")

private String email;

 

  1. 在服務端檢測框架有沒有錯誤,若是有,則進行處理。

驗證框架中若是有錯誤信息,則錯誤信息封裝在一個FieldError對象中,採用鍵值對的形式存儲,鍵就是屬性名: email-->郵箱格式不正確!  封裝成: FieldError

控制器處理:

//@Validated表示此對象要經過驗證框架,BindingResult對象封裝了驗證框架的驗證信息

@RequestMapping(value = "save")

public ModelAndView save(@Validated Student student,BindingResult result,Model model) {

//針對提交的封裝好的實體對象來判斷是否經過了驗證,若是經過則把對象向底層傳。不然返回添加頁面,並提示錯誤信息

if(result.hasErrors()) {

            Map<String, String> errors = new HashMap<String, String>();       

//循環取存儲在 BindingResult對象中封裝的驗證信息

for (FieldError f : result.getFieldErrors()) {

System.out.println(f.getField()+"--"+f.getDefaultMessage());

errors.put(f.getField(), f.getDefaultMessage());

}

 

//年級信息

List<Grade> grades = new GradeServiceImpl().getGrades();

model.addAttribute("student",student);

model.addAttribute("errors",errors);

model.addAttribute("grades",grades);

 

return new ModelAndView("studentAdd");

}else {

//把數據傳向底層,保存到數據庫中。

    return new ModelAndView("redirect:list");

}

}

 

jsp頁面處理:

<form action="/springMVCDemo/student/save" method="post">

    <fieldset>

      <legend>學生基本信息</legend>

      <p>姓名:<input type="text" name="name" value="${student.name }"> <span class="s">${errors.name }</span></p>

      <p>性別:<input type="radio" name="sex" value="男" checked="checked"> 男

             <input type="radio" name="sex" value="女"> 女

      </p>

      <p>年齡:<input type="text" name="age" value="${student.age }"> <span class="s">${errors.age }</span></p>

      <p>電話:<input type="text" name="phone" value="${student.phone }"> <span class="s">${errors.phone }</span></p>

      <p>地址:<input type="text" name="address" value="${student.address }"> <span class="s">${errors.address }</span></p>

      <p>郵箱:<input type="text" name="email" value="${student.email }"> <span class="s">${errors.email }</span></p>

      <p>生日:<input type="text" name="birthday" value="${student.birthday }"></p>

      <p>年級:

          <select name="grade.gradeId">

            <c:forEach items="${grades }" var="g">

              <c:choose>

                <c:when test="${g.gradeId==student.grade.gradeId }">

                   <option value="${g.gradeId }" selected="selected">${g.gradeName }</option>                

                </c:when>

                <c:otherwise>

                   <option value="${g.gradeId }">${g.gradeName }</option>

                </c:otherwise>

              </c:choose>

            </c:forEach>

          </select>

      </p>

      <p>    <input type="submit" value="保 存"></p>

    </fieldset>

  </form>

 

驗證的註解:

@Null                     驗證對象是否爲 null

@NotNull                     驗證對象是否不爲 null

@AssertTrue 驗證 Boolean 對象是否爲 true

@AssertTrue 驗證 Boolean 對象是否爲 false

@Max(value) 驗證 Number String 對象是否小於等於指定值。

@Min(value) 驗證 Number String 對象是否大於等於指定值。

@DecimalMax(value)      驗證註解的元素值小於等於 @DecimalMax 指定的 value 值。

@DecimalMin(value)      驗證註解的元素值大於等於 @DecimalMin 指定的 value 值。

@Digits(integer,fraction)     驗證字符串是否符合指定格式的數字,nteger 指定整數精度,fraction 指定小數精度。

@Size(min,max) 驗證對象長度是否在給定的範圍內。

@Past                     驗證 Date Calendar 對象是否在當前時間以前。

@Future                     驗證 Date Calendar 對象是否在當前時間以後。

@Pattern                     驗證 String 對象是否符合正則表達式的規則。

@NotBlank     檢查字符串是否是 Null,被 Trim 的長度是否大於0

                只對字符串,且會去掉先後空格。

@URL        驗證是不是合法的 url

@Email       驗證是不是合法的郵箱。

@CreditCardNumber 驗證是不是合法的信用卡號。

@Length(min,max) 驗證字符串的長度必須在指定範圍內。

@NotEmpty 檢查元素是否爲 Null Empty

@Range(min,max,message) 驗證屬性值必須在合適的範圍內。

 

做業,完善學生的查詢及添加功能。

2、文件上傳下載

相關文章
相關標籤/搜索