• 五、 配置后端验证功能


    一、添加依赖

    pom.xml 文件中添加依赖,然后让 Maven 加载依赖库。
    1. 1. <dependency>
    2. 2. <groupId>org.springframework.boot</groupId>
    3. 3. <artifactId>spring-boot-starter-validation</artifactId>
    4. 4. </dependency>

    二、创建Form

    validation 库在做后端验证的时候,要求必须用封装类(Form类)来保存客户端提交的数据, 然后在封装类中,我们可以定义验证的规则, validation 会执行这些规则,帮我们验证客户端 提交的数据。

          我们为之前的 TestController 里面的 sayHello() 方法设置一个Form类,接受客户端提交的

    name 数据。我们在 com.example.emos.wx.controller.form 包里面创建 TestSayHelloForm 类。

    1. 1. package com.example.emos.wx.controller.form;
    2. 2. import io.swagger.annotations.ApiModel;
    3. 3. import lombok.Data;
    4. 4. import javax.validation.constraints.NotBlank;
    5. 5. import javax.validation.constraints.Pattern;
    6. 6. @ApiModel
    7. 7. @Data
    8. 8. public class TestSayHelloForm {
    9. 9. @NotBlank
    10. 10. @Pattern(regexp = "^[\\u4e00-\\u9fa5]{2,15}$")
    11. 11. @ApiModelProperty("姓名")
    12. 12. private String name;
    13. 13. }

    三、新建sayValHello()方法

    1. package com.example.emos.wx.controller;
    2. import com.example.emos.wx.common.util.R;
    3. import com.example.emos.wx.controller.form.TestSayHelloForm;
    4. import io.swagger.annotations.Api;
    5. import io.swagger.annotations.ApiOperation;
    6. import org.springframework.web.bind.annotation.*;
    7. import javax.validation.Valid;
    8. @RestController
    9. @RequestMapping("/test")
    10. @Api("测试Web接口")
    11. public class TestController {
    12. @PostMapping("/sayValHello")
    13. @ApiOperation("测试验证假数据")
    14. public R sayValHello(@Valid @RequestBody TestSayHelloForm form) {
    15. return R.ok().put("message","HelloWorld"+form.getName()
    16. );
    17. }
    18. }

    四、执行测试

  • 相关阅读:
    Protocol buffe vs Json 为什么还会大量使用Json?
    Java笔试题
    docker镜像仓库迁移
    天空卫士C++ 一面(技术面、61min)
    threejs 动态调整相机位置,使相机正好能看到对象
    Redis Redis介绍、安装 - Redis客户端
    io_uring异步io简介
    GD32F10 串口通信
    git常用命令
    【算法与数据结构】46、47、LeetCode全排列I, II
  • 原文地址:https://blog.csdn.net/weixin_39309918/article/details/127407797