SpringBoot使用Hibernate-validate

2021-06-07 03:03

阅读:668

标签:pos   bootstra   table   which   container   ping   content   end   not   

  

本篇文章SpringBoot使用Hibernate-validate以及一些常用的校验

 官方Api 访问地址:

http://hibernate.org/validator/


Released under the ASL v2

Application layer agnostic validation

Hibernate Validator allows to express and validate application constraints. The default metadata source are annotations, with the ability to override and extend through the use of XML. It is not tied to a specific application tier or programming model and is available for both server and client application programming. But a simple example says more than 1000 words:

public class Car {

   @NotNull
   private String manufacturer;

   @NotNull
   @Size(min = 2, max = 14)
   private String licensePlate;

   @Min(2)
   private int seatCount;

   // ...
}

Extendable

Hibernate Validator offers a configurable bootstrap API as well as a range of built-in constraints. The latter can easily be extended by creating custom constraints.

Rich metadata API

Hibernate Validator gives access to constraint configuration via a metadata API facilitating, for example, tooling integration.

Reference implementation

Hibernate Validator 6.x is the reference implementation Bean Validation 2.0.

Added value

Hibernate Validator offers additional value on top of the features required by Bean Validation. For example, a programmatic constraint configuration API as well as an annotation processor which plugs into the build process and raises compilation errors whenever constraint annotations are incorrectly used.

Latest news

Hibernate Validator 6.2.0.Final and 7.0.0.Final released

2021-01-06

As of now, you are probably aware of the Jakarta EE 9 effort that aims to provide new foundations for EE innovation. Jakarta EE 9 is...


Hibernate Validator 6.1.7.Final and 6.0.22.Final released

2020-12-16

We just released Hibernate Validator 6.1.7.Final which contains some minor fixes. This is a recommended upgrade for everyone using Hibernate Validator and it is a drop-in...


Hibernate Validator 6.2.0.CR1 and 7.0.0.CR1 released

2020-12-08

As of now, you are probably aware of the Jakarta EE 9 effort that aims to provide new foundations for EE innovation. Jakarta EE 9 is...


Hibernate Validator 6.1.6.Final and 6.0.21.Final released

2020-09-30

We just released Hibernate Validator 6.1.6.Final which contains a few fixes and the new @Normalized constraint. This is a recommended upgrade for everyone using Hibernate Validator...


Hibernate Validator 6.1.5.Final and 6.0.20.Final released

2020-05-07

We just released Hibernate Validator 6.1.5.Final which contains a fix for CVE-2020-10693 and a few other minor fixes. This is a recommended upgrade for everyone using...


Hibernate Validator 6.1.3.Final and 6.0.19.Final released

2020-04-10

We just released Hibernate Validator 6.1.3.Final which contains some fixes for our translations and a performance improvement for validation of executables (i.e. methods and constructors). This...


Other news
 

 

 

 

Maven依赖


SpringBoot2.3.x 以前 如果按照 SpringBoot 的方式引入了 spring-boot-starter-web,则不需要特意引入 spring-boot-starter-validation
SpringBoot2.3.x 以后需要显引入

dependency>
groupId>org.springframework.bootgroupId>
artifactId>spring-boot-starter-validationartifactId>
dependency>

 


 将参数接受实体DTO进行改造

 

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@ApiModel(description = "api模型")
@Data
public class TAccessApiListDTO implements Serializable {

@ApiModelProperty(name = "id",value = "主键id")
@NotNull(message="id不能为空")
private Integer id;

@ApiModelProperty(name = "apiname",value = "api名称")
@Length(max = 50)
@NotBlank(message = "接口名称不能为空")
private String apiname ;


@ApiModelProperty(name = "request_method",value = "请求方式:GET,POST")
@NotBlank(message = "请求方式不能为空")
private String request_method ;


@ApiModelProperty(name = "version",value = "api版本号")
@NotBlank(message = "版本号不能为空")
private String version ;


@ApiModelProperty(name = "apiparameter",value = "api参数")
private String apiparameter ;


@ApiModelProperty(name = "url",value = "url地址")
@NotBlank(message = "接口地址不能为空")
//@Pattern(regexp = "^((https|http)?:\\/\\/)[^\\s]+$",message = "请填写合法的URL")
private String url ;
}

  


接口改造

在接口原有基础上添加注解 @Valid 或者 @Validated(spring 自带的,多了分组功能,其他请自行查资料)

 

@Api(description = "api管理模块")
@RestController
@RequestMapping("/apimanage")
public class ApimanageController {

@Autowired
private ApimanageService apimanageService;

@ApiOperation(value = "api修改")
@PostMapping("/update")
public JsonResult update(@RequestBody @Valid TAccessApiListDTO accessApiListDto){
apimanageService.updateTAccessApiList(accessApiListDto);
return JsonResult.successModelResult(null);
}
}

  

全局异常拦截处理


请在自己原有的全局异常拦截器中新增 MethodArgumentNotValidException 异常的处理

@Slf4j
@RestControllerAdvice 
public class GlobalExceptionHandler {

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public JsonResult validationError(MethodArgumentNotValidException ex) {
FieldError fieldError = ex.getBindingResult().getFieldError();
log.error(fieldError.getField()+fieldError.getDefaultMessage());
return JsonResult.BuildModelResult("9999",false, fieldError.getField()+fieldError.getDefaultMessage(),null);
}
}

  

 
到此 SpringBoot 使用 Hibernate-validate 校验,讲完了

 

常用的校验

1. @NotBlank


适合字符串的非空校验
 

@NotBlank(message = "url不能为空")

  

 

2. @Pattern

使用正则表达式进行校验 例如URL的校验


@Pattern(regexp = "^((https|http)?:\\/\\/)[^\\s]+$",message = "请填写合法的URL")

  

 

3. @regexp

 


 

4. @NotNull


对象不能为 null
 

@NotNull(message="id不能为空")

  


 5. @Length 字符串长度判断
 

@Length(min = 1,max = 500,message = "字符串长度必须在1-500之间")

  


 6. @Size 判断集合的大小
 

@Size(min = 1,max = 100,message = "集合大小必须在1-100之间")

  


 7. @Email 邮箱格式判断
 

@Email(message = "邮箱格式不正确")

  

 

SpringBoot使用Hibernate-validate

标签:pos   bootstra   table   which   container   ping   content   end   not   

原文地址:https://www.cnblogs.com/ios9/p/14591215.html


评论


亲,登录后才可以留言!