springboot2整合hibernate-validator
阿新 • • 發佈:2018-11-03
0.準備
原始碼(基於dev-swagger分支開發 )
https://gitee.com/jsjack_wang/springboot-demo
部落格(springboot2整合swagger)
https://blog.csdn.net/u013219624/article/details/83152692
1.新增Maven依賴
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.0</version> </dependency>
2.自定義Message包裝類 用於返回錯誤資訊
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Message {
private String fieldName;
private String message;
}
3.自定義通用引數錯誤異常
public class InvalidParamException extends RuntimeException { @Getter private String field; @Getter private String defaultMessage; public InvalidParamException(String field, String defaultMessage) { this.field = field; this.defaultMessage = defaultMessage; } }
4.自定義驗證切面ValidatorAspect
@Aspect @Component public class ValidatorAspect { private final static String el = "@annotation(org.springframework.web.bind.annotation.RequestMapping)"; @Around(ValidatorAspect.el) public Object around(ProceedingJoinPoint p) throws Throwable { Object[] args = p.getArgs(); for (Object arg : args) { if (arg instanceof BindingResult) { BindingResult bindingResult = (BindingResult) arg; if (bindingResult.hasErrors()) { throw new InvalidParamException(bindingResult.getFieldError().getField(), bindingResult.getFieldError().getDefaultMessage()); } } } return p.proceed(); } }
5.自定義全域性異常攔截
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@Autowired
private HttpServletRequest request;
@ExceptionHandler(Exception.class)
@ResponseBody
public Message handler(Exception e) {
Message result;
if (e instanceof MethodArgumentNotValidException) {
LOGGER.info(e.getMessage(), e);
BindingResult br = ((MethodArgumentNotValidException) e).getBindingResult();
result = new Message(br.getFieldError().getField(), br.getFieldError().getDefaultMessage());
} else if (e instanceof InvalidParamException) {
LOGGER.info(e.getMessage(), e);
result = new Message(((InvalidParamException) e).getField(), ((InvalidParamException) e).getDefaultMessage());
} else {
LOGGER.error(e.getMessage(), e);
result = new Message("", e.getMessage());
}
return result;
}
}
6.hibernate validator常用註解使用
@Data
public class HibernateValidatorRequest {
@ApiModelProperty("mustTrue必須為true.")
@AssertTrue(message = "mustTrue必須為true.")
private Boolean mustTrue;
@ApiModelProperty("mustFalse必須為false.")
@AssertFalse(message = "mustFalse必須為false.")
private Boolean mustFalse;
@ApiModelProperty("minTen最小值為10.")
@Min(value = 10, message = "minTen最小值為10.")
private Integer minTen;
@ApiModelProperty("maxTen最大值為10.")
@Max(value = 10, message = "maxTen最大值為10.")
private Integer maxTen;
@ApiModelProperty("valueSize 10~20之間.")
@Range(max = 20, min = 10, message = "valueSize 10~20之間.")
private Integer valueSize;
@ApiModelProperty("pastTime必須是過去的時間.")
@Past(message = "pastTime必須是過去的時間.")
private Date pastTime;
@ApiModelProperty("futureTime必須是將來的時間.")
@Future(message = "futureTime必須是將來的時間.")
private Date futureTime;
@ApiModelProperty("nullParam必須為null.")
@Null(message = "nullParam必須為null.")
private String nullParam;
@ApiModelProperty("notNullParam不能為null.")
@NotNull(message = "notNullParam不能為null.")
private String notNullParam;
@ApiModelProperty("字串非null,且長度必須大於0")
@NotBlank(message = "字串非null,且長度必須大於0")
private String notBlank;
@ApiModelProperty("元素必須是電子郵箱地址")
@Email(message = "元素必須是電子郵箱地址")
private String email;
@ApiModelProperty("字串的大小必須在指定的範圍")
@Length(min=2, max=4, message = "字串的大小必須在指定的範圍")
private String length;
@ApiModelProperty("字串必須非空")
@NotEmpty(message = "字串必須非空")
private String notEmpty;
@ApiModelProperty("使用者名稱6~15位, 字母開頭")
@Pattern(regexp = "[a-zA-Z]\\w{5,14}", message = "使用者名稱6~15位, 字母開頭")
private String patternUsername;
}
@RestController
public class TestController {
@ApiOperation(value = "欄位驗證", response = String.class, tags = "僅僅測試Hibernate-validator")
@RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(@Valid @RequestBody HibernateValidatorRequest request) {
return "success";
}
}
7.正確的json
{
"email": "[email protected]",
"futureTime": "2019-10-23T10:55:02.807Z",
"length": "123",
"maxTen": 0,
"minTen": 10,
"mustFalse": false,
"mustTrue": true,
"notBlank": "string",
"notEmpty": "string",
"notNullParam": "string",
"nullParam": null,
"pastTime": "2018-10-23T10:55:02.807Z",
"patternUsername": "string",
"valueSize": 18
}
原始碼 https://gitee.com/jsjack_wang/springboot-demo dev-hibernate-validator分支