=========================
1.入参实体上,对想要校验的字段加注解
package com.sxd.swapping.domain;
import javax.validation.constraints.NotNull;
/**
* @Author: SXD
* @Description: 基础请求Bean
* @Date: create in 2020/1/10 14:27
*/
public class BaseRequestBean {
@NotNull(message = "userId can't be null")
private Long userId;
@NotNull(message = "store can't be null")
private String storeId;
private String userName;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getStoreId() {
return storeId;
}
public void setStoreId(String storeId) {
this.storeId = storeId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
2.校验结果体,装载校验的结果
package com.sxd.swapping.validation;
import java.util.Map;
/**
* 校验结果体
*/
public class ValidationResult {
//校验结果是否有错
private boolean hasErrors = false;
//校验错误信息
private Map errorMsg;
public boolean isHasErrors() {
return hasErrors;
}
public void setHasErrors(boolean hasErrors) {
this.hasErrors = hasErrors;
}
public Map getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(Map errorMsg) {
this.errorMsg = errorMsg;
}
public String getDetailErrorMsg() {
return null != errorMsg ? errorMsg.toString() : null;
}
@Override
public String toString() {
return "ValidationResult [hasErrors=" + hasErrors + ", errorMsg=" + errorMsg + "]";
}
}
3.校验工具类,使用的javax.validation.Validator
package com.sxd.swapping.validation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* @Author: SXD
* @Description: 校验工具类
* @Date: create in 2020/1/10 14:35
*/
public class ValidationUtil {
private static final String OBJ_NULL = "Para";
private static final String OBJ_NULL_ERR_MSG = "validated Object is null";
private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
/**
* 验证指定对象
*
* @param obj
* 需要被验证对象
* @return
*/
public static ValidationResult validateEntity(T obj) {
ValidationResult result = new ValidationResult();
if(!checkObjNull(obj, result)){
Set> set = validator.validate(obj, Default.class);
if (CollectionUtils.isNotEmpty(set)) {
result.setHasErrors(true);
Map errorMsg = new HashMap();
for (ConstraintViolation cv : set) {
errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage());
}
result.setErrorMsg(errorMsg);
}
}
return result;
}
/**
* 验证指定对象的指定属性
*
* @param obj
* 需要被验证对象
* @param propertyName
* 需要验证的属性名称
* @return
*/
public static ValidationResult validateProperty(T obj, String... propertyName) {
ValidationResult result = new ValidationResult();
if(!checkObjNull(obj, result)){
Map errorMsg = new HashMap();
for (String pName : propertyName) {
Set> set = validator.validateProperty(obj, pName, Default.class);
if (CollectionUtils.isNotEmpty(set)) {
result.setHasErrors(true);
for (ConstraintViolation cv : set) {
errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage());
}
}
}
result.setErrorMsg(errorMsg);
}
return result;
}
/**
* 验证指定对象
*
* @param obj
* 需要被验证对象
* @param exceptPropertyName
* 排除属性(不希望验证的属性)
* @return
*/
public static ValidationResult validateEntity(T obj, String... exceptPropertyName) {
ValidationResult result = new ValidationResult();
if(!checkObjNull(obj, result)){
Set> set = validator.validate(obj, Default.class);
if (CollectionUtils.isNotEmpty(set)) {
Map errorMsg = new HashMap();
for (ConstraintViolation cv : set) {
String field = cv.getPropertyPath().toString();
if (!isExcept(field, exceptPropertyName)) {
result.setHasErrors(true);
errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage());
}
}
result.setErrorMsg(errorMsg);
}
}
return result;
}
/**
*
* 判断字段是否属于例外字段列表
*
* @param field
* @param exceptFieldName
* @return true:属于例外字段 false:不是例外字段
* @exception
* @since 1.0.0
*/
private static boolean isExcept(String field, String... exceptFieldName) {
for (String ef : exceptFieldName) {
if (StringUtils.isNotBlank(ef) && ef.equalsIgnoreCase(field)) {
return true;
}
}
return false;
}
/**
* 检查入参是否为null
* @param obj
* @param result
* @param
* @return
*/
private static boolean checkObjNull(T obj,ValidationResult result) {
if (null == obj){
Map errorMsg = new HashMap();
errorMsg.put(OBJ_NULL, OBJ_NULL_ERR_MSG);
result.setErrorMsg(errorMsg);
return true;
}
return false;
}
}
4.在controller中,使用校验工具类对请求入参进行校验
@RequestMapping(value = "/myTest2", method = {RequestMethod.GET,RequestMethod.POST})
public String myTestController2(@RequestBody BaseRequestBean baseRequestBean){
StringBuilder msg = new StringBuilder("访问成功");
ValidationResult validationResult = ValidationUtil.validateEntity(baseRequestBean);
if (validationResult.isHasErrors()){
msg.setLength(0);
msg.append(validationResult.getDetailErrorMsg());
}
return msg.toString();
}
5.校验效果