使用Bean Validation 做RestApi请求数据验证

我们在系统中经常会遇到需要对输入的数据进行验证。

这里我们使用Spring Boot 结合Bean Validation API来进行数据验证。

Bean Validation API是Java定义的一个验证参数的规范。

具体可以参考: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);
    }
}

进行测试看看是我们获得了什么

发送请求

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

可以看到我们的操作是成功的,但是没有对我们的数据进行校验。
现在我们有两个需求:

  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)

就这么简单 我们再看看会发生什么

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": "个数必须在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": "个数必须在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的规则

    @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接口也加上输入数据验证吧~
以上的代码例子 https://github.com/chc123456/ValidatingInputRestRequestSpringBoot/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容