springboot使用校正架構validation校正的樣本,

來源:互聯網
上載者:User

springboot使用校正架構validation校正的樣本,

b/s系統中對http請求資料的校正多數在用戶端進行,這也是出於簡單及使用者體驗性上考慮,但是在一些安全性要求高的系統中服務端校正是不可缺少的。

Spring3支援JSR-303驗證架構,JSR-303 是Java EE 6 中的一項子規範,叫做BeanValidation,官方參考實現是hibernate Validator(與Hibernate ORM 沒有關係),JSR 303 用於對Java Bean 中的欄位的值進行驗證。

Validator主要是校正使用者提交的資料的合理性的,比如是否為空白了,密碼長度是否大於6位,是否是純數位,等等。那麼在spring boot怎麼使用這麼強大的校正架構呢。

validation與 springboot 結合

1. bean 中添加標籤

部分代碼:

標籤需要加在屬性上,@NotBlank 標籤含義文章末尾有解釋

public class User {  private Integer id;  @NotBlank(message = "{user.name.notBlank}")  private String name;  private String username;

2. Controller中開啟驗證

在Controller 中 請求參數上添加@Validated 標籤開啟驗證

  @RequestMapping(method = RequestMethod.POST)  public User create(@RequestBody @Validated User user) {    return userService.create(user);  }

3. resource 下建立錯誤資訊設定檔

在resource 目錄下建立提示資訊設定檔“ValidationMessages.properties“

注意:名字必須為“ValidationMessages.properties“ 因為SpringBoot自動讀取classpath中的ValidationMessages.properties裡的錯誤資訊

ValidationMessages.properties 檔案的編碼為ASCII。資料類型為 key value 。key“user.name.notBlank“為第一步 bean的標籤 大括弧裡面對應message的值

value 為提示資訊 ,但是是ASCII 。(內容為“名字不可為空“)

4. 自訂異常處理器,捕獲錯誤資訊

當驗證不通過時會拋異常出來,異常的message 就是 ValidationMessages.properties 中配置的提示資訊。此處定義異常處理器。捕獲異常資訊(因為驗證不通過的項可能是多個所以統一捕獲處理),並拋給前端。(此處是前後端分離開發)

  public void MethodArgumentNotValidException(Exception ex, HttpServletRequest request, HttpServletResponse response) {    logger.error( ":" + CommonUtil.getHttpClientInfo(request), ex);    MethodArgumentNotValidException c = (MethodArgumentNotValidException) ex;    List<ObjectError> errors =c.getBindingResult().getAllErrors();    StringBuffer errorMsg=new StringBuffer();    errors.stream().forEach(x -> errorMsg.append(x.getDefaultMessage()).append(";"));    pouplateExceptionResponse(response, HttpStatus.INTERNAL_SERVER_ERROR, errorMsg.toString());  } private void pouplateExceptionResponse(HttpServletResponse response, HttpStatus errorCode, String errorMessage) {    try {      response.sendError(errorCode.value(), errorMessage);    } catch (IOException e) {      logger.error("failed to populate response error", e);    }  }

5. 附上部分標籤含義

限制 說明
@Null 限制只能為null
@NotNull 限制必須不為null
@AssertFalse 限制必須為false
@AssertTrue 限制必須為true
@DecimalMax(value) 限制必須為一個不大於指定值的數字
@DecimalMin(value) 限制必須為一個不小於指定值的數字
@Digits(integer,fraction) 限制必須為一個小數,且整數部分的位元不能超過integer,小數部分的位元不能超過fraction
@Future 限制必須是一個將來的日期
@Max(value) 限制必須為一個不大於指定值的數字
@Min(value) 限制必須為一個不小於指定值的數字
@Past 限制必須是一個過去的日期
@Pattern(value) 限制必須符合指定的Regex
@Size(max,min) 限制字元長度必須在min到max之間
@Past 驗證註解的元素值(日期類型)比目前時間早
@NotEmpty 驗證註解的元素值不為null且不為空白(字串長度不為0、集合大小不為0)
@NotBlank 驗證註解的元素值不為空白(不為null、去除首位空格後長度為0),不同於@NotEmpty,@NotBlank只應用於字串且在比較時會去除字串的空格
@Email 驗證註解的元素值是Email,也可以通過Regex和flag指定自訂的email格式

樣本

 @Pattern(regexp="^[a-zA-Z0-9]+$",message="{account.username.space}") @Size(min=3,max=20,message="{account.username.size}")

樣本2

在這裡我們主要是使用註解進行學習。我們先說說我們的需求:

我們有一個demo.html,在頁面上有兩個元素 姓名輸入框,密碼輸入庫,提交按鈕。

提交到後台之後,使用Validator進行校正,然後如果存在錯誤,轉寄到demo.html,

我們先編寫一個實體類接收使用者的輸入,以及使用Validator註解校正:

package com.kfit.demo; import org.hibernate.validator.constraints.Length;import org.hibernate.validator.constraints.NotEmpty; public class Demo {    private long id;   @NotEmpty(message="姓名不可為空")  private String name;    @NotEmpty(message="密碼不可為空")  @Length(min=6,message="密碼長度不能小於6位")  private String password;   publiclong getId() {    return id;  }   publicvoid setId(longid) {    this.id = id;  }   public String getName() {    return name;  }   public void setName(String name) {    this.name = name;  }   public String getPassword() {    return password;  }   public void setPassword(String password) {    this.password = password;  }   @Override  public String toString() {    return "Demo [id=" + id + ", name=" + name + ", password=" + password + "]";  }}

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.