接着之前的学习,本章主要记录SpringBoot整合Validator,实现参数校验。
1、添加依赖
org.springframework.boot
spring-boot-starter-validation
报错 Unresolved dependency
reload project后,出现如下报错
解决办法:Unresolved dependency: 'org.springframework.boot:spring-boot-starter-validation:jar:2.6.6'
1、打开maven工具栏,发现如下错误提示
jar包org.springframework.boot:spring-boot-starter:2.6.6重复了
2、打开project structure -> project Settings -> Libraries,找到org.springframework.boot:spring-boot-starter:2.6.6并删除
3、问题解决,成功启动
2、用户实体类添加校验@Length(max = 8, message = "用户名不能超过8个字符")
@Pattern(regexp = "^[A-Za-z]+$", message = "用户名只能包含字母")
private String username;
@Size(max=8, min = 6)
private String password;
3、在controller内使用@Validated注解使参数校验功能生效
@PostMapping("/add")
@ResponseBody
public Integer addUser(@Validated User user) {
return userserviceImpl.addUser(user);
}
4、测试
测试结果如下图:
后台报错信息如下:
2022-04-22 20:03:19.819 WARN 8016 --- [nio-8081-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errorsField error in object 'user' on field 'username': rejected value [zhangsan03]; codes [Pattern.user.username,Pattern.username,Pattern.java.lang.String,Pattern]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.username,username]; arguments []; default message [username],[Ljavax.validation.constraints.Pattern$Flag;@1742b2d2,^[A-Za-z]+$]; default message [用户名只能包含字母]Field error in object 'user' on field 'username': rejected value [zhangsan03]; codes [Length.user.username,Length.username,Length.java.lang.String,Length]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.username,username]; arguments []; default message [username],8,0]; default message [用户名不能超过8个字符]]
修改用户名,成功添加用户 ^^
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)