We use spring
a tool spring-boot-starter-validation
that provides us with a good unified verification in the background to verify the request.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Several commonly used checks are encapsulated here through annotations
@NotNull
Cannot be null@NotEmpty
Cannot be null, empty string, empty collection@NotBlank
Cannot be null, empty string, pure space string@Min
The minimum value of the number cannot be less than x@Max
Maximum number cannot be greater than x@Email
The string is in the mail format@Max
Maximum number cannot be greater than x@Size
The minimum string length is x, and the minimum collection length is x@Pattern
Regular expression
Let’s take SysUser
an example and see how to use it
public class SysUser implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 用户ID
*
*/
@TableId
private Long userId;
/**
* 用户名
*/
@NotBlank(message="用户名不能为空")
@Size(min = 2,max = 20,message = "用户名长度要在2-20之间")
private String username;
/**
* 密码
*/
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
/**
* 邮箱
*/
@NotBlank(message="邮箱不能为空")
@Email(message="邮箱格式不正确")
private String email;
/**
* 手机号
*/
@Pattern(regexp="0?1[0-9]{10}",message = "请输入正确的手机号")
private String mobile;
/**
* 状态 0:禁用 1:正常
*/
private Integer status;
/**
* 用户所在店铺id
*/
private Long shopId;
/**
* 角色ID列表
*/
@TableField(exist=false)
private List<Long> roleIdList;
/**
* 创建时间
*/
private Date createTime;
}
We use the bean in the Controller layer and use @Valid
annotations to make the verification annotations effective, such as SysUserController
:
@RestController
@RequestMapping("/sys/user")
public class SysUserController {
/**
* 保存用户
*/
@SysLog("保存用户")
@PostMapping
@PreAuthorize("@pms.hasPermission('sys:user:save')")
public ResponseEntity<String> save(@Valid @RequestBody SysUser user){
String username = user.getUsername();
SysUser dbUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
.eq(SysUser::getUsername, username));
if (dbUser!=null) {
return ResponseEntity.badRequest().body("该用户已存在");
}
user.setShopId(SecurityUtils.getSysUser().getShopId());
user.setPassword(passwordEncoder.encode(user.getPassword()));
sysUserService.saveUserAndUserRole(user);
return ResponseEntity.ok().build();
}
}
And DefaultExceptionHandlerConfig
intercept @Valid
the exception information triggered by and return:
@Controller
@RestControllerAdvice
public class DefaultExceptionHandlerConfig {
@ExceptionHandler(BindException.class)
public ResponseEntity<String> bindExceptionHandler(BindException e){
e.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getBindingResult().getFieldErrors().get(0).getDefaultMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
e.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getBindingResult().getFieldErrors().get(0).getDefaultMessage());
}
}