Simplify the verification of parameters
1. Introduce dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.5.RELEASE</version>
</dependency>
2. Add annotations to the class that receives the parameters, specify the verification rules, and prompt messages
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;
@Data
public class Employee {
/** 姓名 */
@NotBlank(message = "请输入名称")
@Length(message = "名称不能超过个 {max} 字符", max = 10)
public String name;
/** 年龄 */
@NotNull(message = "请输入年龄")
@Range(message = "年龄范围为 {min} 到 {max} 之间", min = 1, max = 100)
public Integer age;
/**手机 */
@Length(message = "手机号码格式不正确",min = 11,max = 11)
private String sharePhone;
@NotEmpty(message = "兴趣不能为空")
@Size(message = "兴趣数量不能大于{max}个",max = 10)
private List<String> hobbyList;
}
3. In the controller method, the parameter is received and annotated @Valid
indicates that the parameter receiving object will be constrained
@PostMapping
@ApiOperation(value = "新增数据")
public Result insert(@Valid @RequestBody Employee employee) {
//方法体省略...
}