@NotBlank使用时无效问题解决。
引入依赖
问题解决之前一直调试都没有发现依赖的问题,后来也是看评论中有人遇到同样的问题,才发现依赖不对。
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
|
实体类注解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @Data public class User implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO) private Long id;
@NotBlank(message="昵称不能为空") private String username;
private String avatar;
@NotBlank(message = "邮箱不能为空") @Email(message = "邮箱格式不正确") private String email;
private String password; }
|
判断字段为空的三种注解:
@NotBlank:只用在String上,表示传进来的值不能为null,而且调用trim()后,长度必须大于0
@NotNull:不能为null,但可以为empty(分配了内存空间,但值为空)
@NotEmpty:不能为null,而且长度必须大于0
参数注解
1 2 3 4
| @PostMapping("/save") public Result save(@Validated @RequestBody User user){ return Result.succ(user); }
|
也可以使用@Valid注解参数,@Validated注解Service层。经试验同样有效。