一、添加依赖
在
pom.xml
文件中添加依赖,然后让
Maven
加载依赖库。
1. <dependency>
2. <groupId>org.springframework.boot</groupId>
3. <artifactId>spring-boot-starter-validation</artifactId>
4. </dependency>
二、创建Form类
validation 库在做后端验证的时候,要求必须用封装类(Form类)来保存客户端提交的数据, 然后在封装类中,我们可以定义验证的规则, validation 会执行这些规则,帮我们验证客户端 提交的数据。
我们为之前的 TestController 里面的 sayHello() 方法设置一个Form类,接受客户端提交的
name 数据。我们在 com.example.emos.wx.controller.form 包里面创建 TestSayHelloForm 类。
1. package com.example.emos.wx.controller.form;
2. import io.swagger.annotations.ApiModel;
3. import lombok.Data;
4. import javax.validation.constraints.NotBlank;
5. import javax.validation.constraints.Pattern;
6. @ApiModel
7. @Data
8. public class TestSayHelloForm {
9. @NotBlank
10. @Pattern(regexp = "^[\\u4e00-\\u9fa5]{2,15}$")
11. @ApiModelProperty("姓名")
12. private String name;
13. }
三、新建sayValHello()方法
package com.example.emos.wx.controller;
import com.example.emos.wx.common.util.R;
import com.example.emos.wx.controller.form.TestSayHelloForm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@RestController
@RequestMapping("/test")
@Api("测试Web接口")
public class TestController {
@PostMapping("/sayValHello")
@ApiOperation("测试验证假数据")
public R sayValHello(@Valid @RequestBody TestSayHelloForm form) {
return R.ok().put("message","HelloWorld"+form.getName()
);
}
}
四、执行测试