使用这个工具可以在后端完成对参数的校验以及响应
<javax.validation.version>2.0.0.Final</javax.validation.version>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>${javax.validation.version}</version>
</dependency>
然后在你的前端来参的dto中进行如下配置
@Data
public class LoginDto {
@NotBlank(message = "账号必须填写")
@Length(min = 8, max = 32, message = "限制8-32位字符")
private String username;
@NotBlank(message = "密码不能为空或者空格")
@Pattern(regexp = "[A-Za-z0-9]+", message = "必须由数字和字母组成")
@Length(min = 8, max = 32, message = "长度限制8-32位字符")
private String password;
}
接口参数前加上注解@Valid
@PostMapping("login")
public String login(@RequestBody @Valid LoginDto loginDto){
System.out.println(loginDto);
return "SUCCESS";
}
字符串的规则校验:
@PostMapping("/soutaaa")
public String soutaaa(@RequestBody String aaa){
String regex="^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$";
String str="执行成功!";
if(!aaa.matches(regex))
str="格式错误!";
return str;
}
|