【java】【校验】使用java自带的Validator完成字段校验,完成请求入参属性校验


 

=========================

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; } }
View Code

 

 

2.校验结果体,装载校验的结果

package com.sxd.swapping.validation; import java.util.Map; /** * 校验结果体 */
public class ValidationResult { //校验结果是否有错 
    private boolean hasErrors = false; //校验错误信息 
    private Map<String, String> errorMsg; public boolean isHasErrors() { return hasErrors; } public void setHasErrors(boolean hasErrors) { this.hasErrors = hasErrors; } public Map<String, String> getErrorMsg() { return errorMsg; } public void setErrorMsg(Map<String, String> errorMsg) { this.errorMsg = errorMsg; } public String getDetailErrorMsg() { return null != errorMsg ? errorMsg.toString() : null; } @Override public String toString() { return "ValidationResult [hasErrors=" + hasErrors + ", errorMsg=" + errorMsg + "]"; } }
View Code

 

 

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 <T> ValidationResult validateEntity(T obj) { ValidationResult result = new ValidationResult(); if(!checkObjNull(obj, result)){ Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class); if (CollectionUtils.isNotEmpty(set)) { result.setHasErrors(true); Map<String, String> errorMsg = new HashMap<String, String>(); for (ConstraintViolation<T> cv : set) { errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage()); } result.setErrorMsg(errorMsg); } } return result; } /** * 验证指定对象的指定属性 * * @param obj * 需要被验证对象 * @param propertyName * 需要验证的属性名称 * @return
     */
    public static <T> ValidationResult validateProperty(T obj, String... propertyName) { ValidationResult result = new ValidationResult(); if(!checkObjNull(obj, result)){ Map<String, String> errorMsg = new HashMap<String, String>(); for (String pName : propertyName) { Set<ConstraintViolation<T>> set = validator.validateProperty(obj, pName, Default.class); if (CollectionUtils.isNotEmpty(set)) { result.setHasErrors(true); for (ConstraintViolation<T> cv : set) { errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage()); } } } result.setErrorMsg(errorMsg); } return result; } /** * 验证指定对象 * * @param obj * 需要被验证对象 * @param exceptPropertyName * 排除属性(不希望验证的属性) * @return
     */
    public static <T> ValidationResult validateEntity(T obj, String... exceptPropertyName) { ValidationResult result = new ValidationResult(); if(!checkObjNull(obj, result)){ Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class); if (CollectionUtils.isNotEmpty(set)) { Map<String, String> errorMsg = new HashMap<String, String>(); for (ConstraintViolation<T> 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 <T> * @return
     */
    private static <T> boolean checkObjNull(T obj,ValidationResult result) { if (null == obj){ Map<String, String> errorMsg = new HashMap<String, String>(); errorMsg.put(OBJ_NULL, OBJ_NULL_ERR_MSG); result.setErrorMsg(errorMsg); return true; } return false; } }
View Code

 

 

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(); }
View Code

 

 

5.校验效果

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM