参数校验: spring-boot-starter-validation
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
应用
@PostMapping("/login")
public Result login(@Pattern(regexp = "^\\S{5,15}$") String username,
@Pattern(regexp = "^\\S{5,15}$") String password) {
...........
}
@PutMapping("/update")
public Result update(@RequestBody @Validated User user) {
userService.update(user);
return Result.suc();
}
实体类
@Data
public class User {
@NotNull
@TableId
Integer id;
String username;
@JsonIgnore
String password;
@NotEmpty
@Pattern(regexp="^\\S{1,10}$")
String nickname;
@NotEmpty
@Email
String email;
String userPic;
LocalDateTime createTime;
LocalDateTime updateTime;
}
# 分组校验
@Data
public class Category {
@NotNull(groups = Update.class)
@TableId(type = IdType.AUTO)
Integer id;
@NotEmpty
String categoryName;
@NotNull
String categoryAlias;
Integer createUser;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
LocalDateTime createTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
LocalDateTime updateTime;
public interface Add extends Default {
}
public interface Update extends Default {
}
}