首先在实体类中添加注解@NotEmpty等注解 下面是我的示例
@Data
@ApiModel("登录信息")
public class UserLoginDTO implements Serializable {
private static final long serialVersionUID = 6172547632455570758L;
@ApiModelProperty("用户名")
@NotEmpty(message = "用户名不能为空")
private String username;
@ApiModelProperty("密码")
@NotEmpty(message = "密码不能为空")
@Size(min = 6,max = 20,message = "密码长度应该为6到20位")
private String password;
}
下面总结一下 这类注解
包括下面这些
javax.validation.constraints.xxx
注解 | 说明 |
---|---|
@Null | 被注释的元素必须为null |
@NotNull | 被注释的元素不能为null |
@AssertTrue | 被注释的元素必须为true |
@AssertFalse | 被注释的元素必须为false |
@Min(value) | 被注释的元素必须是一个数字,其值必须大于等于指定的最小值 |
@Max(value) | 被注释的元素必须是一个数字,其值必须小于等于指定的最大值 |
@DecimalMin(value) | 被注释的元素必须是一个数字,其值必须大于等于指定的最小值 |
@DecimalMax(value) | 被注释的元素必须是一个数字,其值必须小于等于指定的最大值 |
@Size(max,min) | 被注释的元素的大小必须在指定的范围内。 |
@Digits(integer,fraction) | 被注释的元素必须是一个数字,其值必须在可接受的范围内 |
@Past | 被注释的元素必须是一个过去的日期 |
@Future | 被注释的元素必须是一个将来的日期 |
@Pattern(value) | 被注释的元素必须符合指定的正则表达式。 |
被注释的元素必须是电子邮件地址 | |
@Length | 被注释的字符串的大小必须在指定的范围内 |
@NotEmpty | 被注释的字符串必须非空 |
@Range | 被注释的元素必须在合适的范围内 |
上面注解的总结转载于java 校验注解之 @NotNull、@NotBlank、@NotEmpty_java notnull-优快云博客
上面的注解需要配合@Validated注解使用 在controller层 使用此注解可以校验前端传过来的参数
这里简单谈一下@Validated和@Valid的区别:
@Validated:可以用在类型、方法和方法参数上。但是不能用在成员属性(字段)上
@Valid:可以用在方法、构造函数、方法参数和成员属性(字段)上
下面是@Validated在controller层中使用的示例
@ApiOperation("用户登录信息")
@RequestMapping(path = "/login",method = RequestMethod.POST)
public Result<String> userLogin(@RequestBody @Validated UserLoginDTO userLoginDTO, HttpSession session){
String result = userService.userLogin(userLoginDTO,session);
return new Result<>(CodeNum.SUCCESS_CODE, ResultConstant.LOGIN_SUCCESS,result);
}
最后我们可以通过全局异常的抓取 返回结果
这里 @Validated 会抛出BindException,MethodArgumentNotValidException,ConstraintViolationException三种异常
这里我以MethodArgumentNotValidException为例,
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public Result<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
List<ObjectError> errors = ex.getBindingResult().getAllErrors();
StringBuilder errorMsg = new StringBuilder();
errors.forEach(error -> errorMsg.append(error.getDefaultMessage()).append(";"));
log.error(errorMsg.toString());
return new Result<>(CodeNum.ERROR_CODE,errorMsg.toString(),null);
}
下面来测试一下
返回的结果
成功完成参数校验!
以上就是我总结的后端参数校验的解决方法 请大佬们指正!