使用Bean Validation 做RestApi請求數(shù)據(jù)驗證

我們在系統(tǒng)中經(jīng)常會遇到需要對輸入的數(shù)據(jù)進行驗證寞钥。

這里我們使用Spring Boot 結合Bean Validation API來進行數(shù)據(jù)驗證声怔。

Bean Validation API是Java定義的一個驗證參數(shù)的規(guī)范呵扛。

具體可以參考:http://beanvalidation.org/specification/

依賴

在pom文件中加入spring-boot-starter-validation

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

定義請求

例子中我們定義如下的請求消息宛篇。它包含id就轧,username,password 三個屬性腋妙。

package com.github.alex.validate.model;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 * Created by ChenChang on 2017/4/8.
 */
public class UserRequest {
    private Long id;   
    private String username;
    private String password;


    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

編寫Controller

我們使用Spring 提供的@RestController注解。

做一個簡單的CURD的Controller讯榕,如下

package com.github.alex.validate.web;

import com.github.alex.validate.model.User;
import com.github.alex.validate.model.UserRequest;
import com.github.alex.validate.util.HeaderUtil;
import com.github.alex.validate.util.IdWorker;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import io.swagger.annotations.ApiOperation;

/**
 * Created by ChenChang on 2017/4/8.
 */

@RestController
@RequestMapping(value = "/userResource")
public class UserResource {
    private final Logger log = LoggerFactory.getLogger(UserResource.class);
    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());
    IdWorker idWorker = new IdWorker(2);

    @PostMapping
    @ApiOperation(value = "新增用戶", notes = "新增用戶")
    public ResponseEntity<User> createUser(@RequestBody UserRequest request) throws URISyntaxException {
        log.debug("REST request to create User: {}", request);
        User user = new User();
        BeanUtils.copyProperties(request, user);
        user.setId(idWorker.nextId());
        users.put(user.getId(), user);
        return ResponseEntity.created(new URI("/userResource/" + user.getId()))
                .headers(HeaderUtil.createEntityCreationAlert(User.class.getSimpleName(), user.getId().toString()))
                .body(user);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "獲取用戶", notes = "獲取用戶")
    public ResponseEntity<User> getUser(@PathVariable  Long id) {
        log.debug("REST request to get User : {}", id);
        User user = users.get(id);
        return Optional.ofNullable(user)
                .map(result -> new ResponseEntity<>(
                        result,
                        HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    @PutMapping
    @ApiOperation(value = "更新用戶", notes = "更新用戶")
    public ResponseEntity<User> updateUser(@RequestBody UserRequest request)
            throws URISyntaxException {
        log.debug("REST request to update User : {}", request);
        if (request.getId() == null) {
            return ResponseEntity.badRequest().body(null);
        }
        User user = users.get(request.getId());
        BeanUtils.copyProperties(request, user);
        return ResponseEntity.ok()
                .headers(HeaderUtil.createEntityUpdateAlert(User.class.getSimpleName(), user.getId().toString()))
                .body(user);
    }
}

進行測試看看是我們獲得了什么

發(fā)送請求

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{  \ 
   "password": "1", \ 
   "username": "string" \ 
 }' 'http://localhost:8080/userResource'

獲得了結果

Response Body
{
  "id": 2128081075062784,
  "username": "string",
  "password": "1"
}
Response Code
201

可以看到我們的操作是成功的骤素,但是沒有對我們的數(shù)據(jù)進行校驗。
現(xiàn)在我們有兩個需求:

  1. username不能為空愚屁,并且長度大于三個字母
  2. password不能為空济竹,并且長度大于6小于30

定義驗證

修改UserRequest,在username和password屬性上添加注解

    @NotNull
    @Size(min = 3)
    private String username;
    @NotNull
    @Size(min = 6, max = 30)
    private String password;

修改UserResource,在@RequestBody前面添加注解@Validated

 public ResponseEntity<User> createUser(@Validated @RequestBody UserRequest request)

就這么簡單 我們再看看會發(fā)生什么

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{  \ 
   "password": "1", \ 
   "username": "1" \ 
 }' 'http://localhost:8080/userResource'

結果

Response Body
{
  "timestamp": 1491642036689,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.bind.MethodArgumentNotValidException",
  "errors": [
    {
      "codes": [
        "Size.userRequest.username",
        "Size.username",
        "Size.java.lang.String",
        "Size"
      ],
      "arguments": [
        {
          "codes": [
            "userRequest.username",
            "username"
          ],
          "arguments": null,
          "defaultMessage": "username",
          "code": "username"
        },
        2147483647,
        3
      ],
      "defaultMessage": "個數(shù)必須在3和2147483647之間",
      "objectName": "userRequest",
      "field": "username",
      "rejectedValue": "1",
      "bindingFailure": false,
      "code": "Size"
    },
    {
      "codes": [
        "Size.userRequest.password",
        "Size.password",
        "Size.java.lang.String",
        "Size"
      ],
      "arguments": [
        {
          "codes": [
            "userRequest.password",
            "password"
          ],
          "arguments": null,
          "defaultMessage": "password",
          "code": "password"
        },
        30,
        6
      ],
      "defaultMessage": "個數(shù)必須在6和30之間",
      "objectName": "userRequest",
      "field": "password",
      "rejectedValue": "1",
      "bindingFailure": false,
      "code": "Size"
    }
  ],
  "message": "Validation failed for object='userRequest'. Error count: 2",
  "path": "/userResource"
}
Response Code
400

其他驗證

hibernate-validator也對Bean Validation做了支持,增加了更多種類的驗證
我們在UserRequest中加入新的字段email,它是一個必填項霎槐,而且要符合email的規(guī)則

    @Email
    @NotNull
    private String email;

再來試試

Response Body
{
  "timestamp": 1491642643358,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.bind.MethodArgumentNotValidException",
  "errors": [
    {
      "codes": [
        "Email.userRequest.email",
        "Email.email",
        "Email.java.lang.String",
        "Email"
      ],
      "arguments": [
        {
          "codes": [
            "userRequest.email",
            "email"
          ],
          "arguments": null,
          "defaultMessage": "email",
          "code": "email"
        },
        [],
        {
          "codes": [
            ".*"
          ],
          "arguments": null,
          "defaultMessage": ".*"
        }
      ],
      "defaultMessage": "不是一個合法的電子郵件地址",
      "objectName": "userRequest",
      "field": "email",
      "rejectedValue": "string",
      "bindingFailure": false,
      "code": "Email"
    }
  ],
  "message": "Validation failed for object='userRequest'. Error count: 1",
  "path": "/userResource"
}
Response Code
400

如此簡單-,- 給你的Rest接口也加上輸入數(shù)據(jù)驗證吧~
以上的代碼例子 https://github.com/chc123456/ValidatingInputRestRequestSpringBoot/

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末送浊,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子丘跌,更是在濱河造成了極大的恐慌罕袋,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,681評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件碍岔,死亡現(xiàn)場離奇詭異浴讯,居然都是意外死亡,警方通過查閱死者的電腦和手機蔼啦,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,205評論 3 399
  • 文/潘曉璐 我一進店門榆纽,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人捏肢,你說我怎么就攤上這事奈籽。” “怎么了鸵赫?”我有些...
    開封第一講書人閱讀 169,421評論 0 362
  • 文/不壞的土叔 我叫張陵衣屏,是天一觀的道長。 經(jīng)常有香客問我辩棒,道長狼忱,這世上最難降的妖魔是什么膨疏? 我笑而不...
    開封第一講書人閱讀 60,114評論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮钻弄,結果婚禮上佃却,老公的妹妹穿的比我還像新娘。我一直安慰自己窘俺,他們只是感情好饲帅,可當我...
    茶點故事閱讀 69,116評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著瘤泪,像睡著了一般灶泵。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上对途,一...
    開封第一講書人閱讀 52,713評論 1 312
  • 那天赦邻,我揣著相機與錄音,去河邊找鬼掀宋。 笑死深纲,一個胖子當著我的面吹牛仲锄,可吹牛的內容都是我干的劲妙。 我是一名探鬼主播,決...
    沈念sama閱讀 41,170評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼儒喊,長吁一口氣:“原來是場噩夢啊……” “哼镣奋!你這毒婦竟也來了?” 一聲冷哼從身側響起怀愧,我...
    開封第一講書人閱讀 40,116評論 0 277
  • 序言:老撾萬榮一對情侶失蹤侨颈,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后芯义,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體哈垢,經(jīng)...
    沈念sama閱讀 46,651評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,714評論 3 342
  • 正文 我和宋清朗相戀三年扛拨,在試婚紗的時候發(fā)現(xiàn)自己被綠了耘分。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,865評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡绑警,死狀恐怖求泰,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情计盒,我是刑警寧澤渴频,帶...
    沈念sama閱讀 36,527評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站北启,受9級特大地震影響卜朗,放射性物質發(fā)生泄漏拔第。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,211評論 3 336
  • 文/蒙蒙 一聊替、第九天 我趴在偏房一處隱蔽的房頂上張望楼肪。 院中可真熱鬧,春花似錦惹悄、人聲如沸春叫。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,699評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽暂殖。三九已至,卻和暖如春当纱,著一層夾襖步出監(jiān)牢的瞬間呛每,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,814評論 1 274
  • 我被黑心中介騙來泰國打工坡氯, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留晨横,地道東北人。 一個月前我還...
    沈念sama閱讀 49,299評論 3 379
  • 正文 我出身青樓箫柳,卻偏偏與公主長得像手形,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子悯恍,可洞房花燭夜當晚...
    茶點故事閱讀 45,870評論 2 361

推薦閱讀更多精彩內容