1、jar包依赖
<!-- validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
2.Controller层的使用
@PostMapping
@ApiOperation(value = "新增信息", notes = "新增信息")
public ResultBody addUser(@RequestBody @Valid BirdsInfoReq birdsInfoReq) {
//TODO 如果不使用@Valid消炎的话 就会如下写多个if判断
if(StringUtils.isEmpty(birdsInfoReq.getBirdName())){
return ResultBody.failed().msg("名称不能为空");
}
if(StringUtils.isEmpty(birdsInfoReq.getPinyinName())){
return ResultBody.failed().msg("拼音名称不能为空");
}
String handleUser = UserContextHolder.getUserId();
if(baseBirdsInfoDatService.addBirdsInfoDat(handleUser, birdsInfoReq)){
return ResultBody.ok();
}
return ResultBody.failed();
}
这里需要注意的是一定要加
@Valid 注解
3.request请求体中调用
@ApiModel("添加请求类")
@Data
public class BirdsInfoReq {
@NotBlank(message = "名称不能为空")
@ApiModelProperty(value = "名称", required = true)
private String birdName;
@ApiModelProperty(value = "拼音")
private String pinyinName;
@ApiModelProperty(value = "拉丁名字")
private String latinName;
@NotBlank(message = "分类不能为空")
@ApiModelProperty(value = "分类(key)", required = true)
private String birdClassifyKey;
@NotBlank(message = "保护等级不能为空")
@ApiModelProperty(value = "保护等级(key)", required = true)
private String protectKey;
@NotBlank(message = "IUCN等级不能为空")
@ApiModelProperty(value = "IUCN等级(key)", required = true)
private String iucnKey;
/**
* 请求对象中包含有对象,需要再该对象上也加入@Valid 注解
*/
@Valid
@ApiModelProperty(value = "自然光信息", required = true)
private Test test;
}
4、初次验证
可以看到这并不是我们想要的返回格式, 接下来就需要加一个处理器了
6. ValidationExceptionHandler
package com.wh.whcloud.xinzhai.configuration.validate.handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 解决 @Valid 注解效验返回值问题
*
* @author
* @since 2023-02-09
*/
@Controller
@ControllerAdvice
public class ValidationExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public ResultBody handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
BindingResult bindingResult = ex.getBindingResult();
StringBuilder errorMessage = new StringBuilder(bindingResult.getFieldErrors().size() * 16);
for (int i = 0; i < bindingResult.getFieldErrors().size(); i++) {
if (i > 0) {
errorMessage.append(",");
}
FieldError fieldError = bindingResult.getFieldErrors().get(i);
errorMessage.append(fieldError.getDefaultMessage());
}
ResultBody msg = ResultBody.failed().msg(errorMessage.toString());
logger.info("paramValidateError:{}", msg);
return msg;
}
}
全局ResultBody(供参考)
package com.wh.whcloud.core.restful;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.Maps;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Map;
import java.util.ResourceBundle;
/**
* @author
*/
@ApiModel(value = "响应结果")
@Data
public class ResultBody<T> implements Serializable {
private static final long serialVersionUID = -6190689122701100762L;
/**
* 响应编码
*/
@ApiModelProperty(value = "响应编码:0-请求处理成功")
private Integer code = 0;
/**
* 提示消息
*/
@ApiModelProperty(value = "提示消息")
private String message;
/**
* 请求路径
*/
@ApiModelProperty(value = "请求路径")
private String path;
/**
* 响应数据
*/
@ApiModelProperty(value = "响应数据")
private T data;
/**
* http状态码
*/
private Integer httpStatus;
/**
* 附加数据
*/
@ApiModelProperty(value = "附加数据")
private Map<String, Object> extra;
/**
* 响应时间
*/
@ApiModelProperty(value = "响应时间")
private Long timestamp = System.currentTimeMillis();
@JSONField(serialize = false, deserialize = false)
@JsonIgnore
public Integer getHttpStatus() {
return httpStatus;
}
@JSONField(serialize = false, deserialize = false)
@JsonIgnore
public boolean isOk() {
return this.code == ErrorCode.OK.getCode();
}
public static ResultBody ok() {
return new ResultBody().code(ErrorCode.OK.getCode());
}
public static ResultBody failed() {
return new ResultBody().code(ErrorCode.FAIL.getCode());
}
public ResultBody code(Integer code) {
this.code = code;
return this;
}
public ResultBody msg(String message) {
if (message == null) {
message = "";
}
this.message = i18n(message,message);
return this;
}
public ResultBody data(T data) {
this.data = data;
return this;
}
public ResultBody path(String path) {
this.path = path;
return this;
}
public ResultBody httpStatus(int httpStatus) {
this.httpStatus = httpStatus;
return this;
}
public ResultBody put(String key, Object value) {
if (this.extra == null) {
this.extra = Maps.newHashMap();
}
this.extra.put(key, value);
return this;
}
}
7、再次测试
常用的效验注解:
@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) 被注释的元素必须符合指定的正则表达式。
@Email 被注释的元素必须是电子邮件地址
@Length 被注释的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串必须非空
@Range 被注释的元素必须在合适的范围内