0.准备
源码(基于dev-swagger分支开发 )
https://gitee.com/jsjack_wang/springboot-demo
博客(springboot2整合swagger)
https://blog.csdn.net/u013219624/article/details/83152692
1.添加Maven依赖
org.aspectj
aspectjweaver
1.9.0
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分支