对于客户端提交表单或者Ajax中的数据,后端的Controller必须先要做验证,然后才能使用这些数据。
既然要验证数据,那么不妨我们来使用一下Validation库。
一、添加依赖
在pom.xml
文件中添加依赖,然后让Maven加载依赖库。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
二、创建Form类
validation
库在做后端验证的时候,要求必须用封装类(Form类)来保存客户端提交的数据。
然后在封装类中,我们可以定义验证的规则,validation会执行这些规则,帮我们验证客户端提交的数据。
我们为之前的TestController
里面的sayHello()
方法设置一个Form类,接受客户端提交的name
数据。我们在com.example.emos.wx.controller.form
包里面创建TestSayHelloForm
类。
package com.example.emos.wx.controller.form;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
@ApiModel
@Data
public class TestSayHelloForm {
@NotBlank
@Pattern(regexp = "^[\\u4e00-\\u9fa5]{2,15}$")
@ApiModelProperty("姓名")
private String name;
}
三、修改sayHello()方法
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;
import javax.validation.Validation;
@RestController
@RequestMapping("/test")
@Api("测试Web接口")
public class TestController {
@PostMapping("/sayHello")
@ApiOperation("最简单的测试方法")
public R sayHello(@Valid @RequestBody TestSayHelloForm form){
return R.ok().put("message","Hello,"+form.getName());
}
}