validation注解
常用注解
constraint | 说明 | 支持类型 |
---|---|---|
@Null | 被注释的元素必须为null | Object |
@NotNull | 被注释的元素不能为null,但可以为empty,没有Size的约束 | Object |
@NotEmpty | [字符串、数组、集合、Map]不能为null&长度不为0 | 字符串、Object[]、基础类型数组、[Collection、Map]接口实现类 |
@NotBlank | 只用于String,不能为null且trim()之后size>0 | 字符串 |
@Length | 字符串长度为min至max之间 | 字符串 |
@Size(max,min) | [字符串、数组、集合、Map]长度为min至max之间 | 字符串、Object[]、基础类型数组、[Collection、Map]接口实现类 |
@Range | [字符串、数字]大小在min和max之间,字符串必须是数字格式 | 数值、数值格式的字符串 |
@AssertTrue | 被注释的元素必须为true | boolean |
@AssertFalse | 被注释的元素必须为false | boolean |
@Min(value) | [字符串长度、数字]不能小于value | 数值、数值格式的字符串 |
@Max(value) | [字符串长度、数字]不能大于value | 数值、数值格式的字符串 |
@DecimalMin(value) | 被注释的元素必须是一个数字,不能小于等于value; inclusive为false时, 不能小于value | 数值、数值格式的字符串 |
@DecimalMax(value) | 被注释的元素必须是一个数字,不能大于等于value; inclusive为false时, 不能大于value | 数值、数值格式的字符串 |
@Digits(integer,fraction) | 被注释的元素必须是一个数字,其值必须在可接受的范围内,整数位数不能大于integer, 小数位数不能大于fraction | 数值、数值格式的字符串 |
@Past | 被注释的元素必须是一个过去的日期 | 时间 |
@PastOrPresent | 只能是过去时间或当前时间 | 时间 |
@Future | 被注释的元素必须是一个将来的日期 | 时间 |
@FutureOrPresent | 只能是未来时间或当前时间 | 时间 |
@Pattern(value) | 被注释的元素必须符合指定的正则表达式 | 字符串 |
被注释的元素必须是电子邮件地址,可以使用regex指定格式 | 字符串 | |
@Negative | 只能为负数 | 数值 |
@NegativeOrZero | 只能为负数或0 | 数值 |
@Positive | 只能为正数 | 数值 |
@PositiveOrZero | 只能为正数或0 | 数值 |
使用@Valid
或者 @Validated
验证。
使用@RequestBody
验证body数据。
模式
- 效验模式:如果出现多个字段效验失败,会返回所有的验证失败错误信息。通常情况下,当第一个字段/参数效验失败时,直接返回。
- 普通模式:默认使用的就是普通模式,校验完所有的属性之后,返回所有的验证失败信息。
- 快速失败模式:只要有一个字段效验失败,直接返回。
快速失败模式配置
@Configuration
public class ValidationConfig {
/**
* 效验@RequestBody时,采用快速失败模式
*/
@Bean
public Validator validator() {
ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
.configure()
//快速失败
.failFast(true)
.buildValidatorFactory();
return validatorFactory.getValidator();
}
/**
* 效验@RequestParam时,采用快速失败模式
*/
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor(Validator validator) {
MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
// 设置validator
postProcessor.setValidator(validator);
return postProcessor;
}
}
举例
- UsersController
package com.chenglulu.controller.users;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping( value = "/", produces = {MediaType.APPLICATION_JSON_VALUE})
public class UsersController {
@RequestMapping(value = "/register", method = RequestMethod.POST)
public void registerUser(HttpServletRequest request, @Validated @RequestBody RegisterUsersParams params){
}
}
- RegisterUsersParams
package com.chenglulu.controller.users.domain;
import com.chenglulu.constant.Validation;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
@Data
public class RegisterUsersParams {
@NotBlank(message = "username is blank")
private String username;
@NotBlank(message = "phone is blank")
@Pattern(regexp = Validation.PHONE)
private String phone;
@Email
private String email;
}
全局异常处理
常用注解
@ControllerAdvice
@ExceptionHandler 异常类型
@ResponseStatus 异常响应状态
@ResponseBody
举例
package com.chenglulu.exception;
import com.chenglulu.constant.Constants;
import com.chenglulu.constant.ErrorCode;
import com.chenglulu.controller.users.domain.BaseResponse;
import com.chenglulu.utils.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.support.RequestContextUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Locale;
@ControllerAdvice
public class GlobalExceptionHandler {
@Autowired
private MessageSource messageSource;
/**
* 未知异常处理
* @param request 请求
* @param ex 异常对象
*/
@ExceptionHandler(value = {MethodArgumentNotValidException.class})
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public HttpEntity<BaseResponse> handlerMethodArgumentNotValidException(HttpServletRequest request, MethodArgumentNotValidException ex){
String requestId = getRequestIdHeader(request);
String code = ErrorCode.PARAMETER_ERROR;
Locale locale = RequestContextUtils.getLocale(request);
BindingResult br = ex.getBindingResult();
StringBuilder msgStr = new StringBuilder();
List<FieldError> feList = br.getFieldErrors();
for (FieldError fe : feList) {
String message = fe.getDefaultMessage();
String field = fe.getField();
msgStr.append(field).append(message).append("; ");
}
Object[] msgArg = new Object[]{msgStr};
String message = messageSource.getMessage(code, msgArg, locale);
BaseResponse res = ResponseUtil.error(requestId, code, message);
return new HttpEntity<BaseResponse>(res);
}
/**
* 未知异常处理
* @param request 请求
* @param ex 异常对象
*/
@ExceptionHandler(value = {Exception.class})
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public HttpEntity<BaseResponse> handlerException(HttpServletRequest request, Exception ex){
String requestId = getRequestIdHeader(request);
String code = ErrorCode.UNKNOWN_ERROR;
BaseResponse res = ResponseUtil.error(request, requestId, code, null);
return new HttpEntity<BaseResponse>(res);
}
private String getRequestIdHeader(HttpServletRequest request) {
return request.getHeader(Constants.HEADER_X_REQUEST_ID);
}
private String getLocaleMessage(HttpServletRequest request) {
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。