validatorUtil 工具类校验fastjson转对象的参数

  1. 工具类
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import javax.validation.Validation;
import java.util.Set;

public class ValidatorUtil {
    /**
     * 开启快速结束模式 failFast (true)
     */
    private static final Validator validator = Validation.byProvider(HibernateValidator.class).configure().failFast(false).buildValidatorFactory().getValidator();

    /**
     * 校验对象
     *
     * @param t bean
     * @param groups 校验组
     * @return ValidResult
     */
    public static <T> ValidResult validateBean(T t, Class<?>...groups) {
        ValidResult result = new ValidResult();
        Set<ConstraintViolation<T>> violationSet = validator.validate(t,groups);
        boolean hasError = violationSet != null && violationSet.size() > 0;
        result.setHasErrors(hasError);
        if (hasError) {
            for (ConstraintViolation<T> violation : violationSet) {
                result.addError(violation.getPropertyPath().toString(), violation.getMessage());
            }
        }
        return result;
    }
    /**
     * 校验bean的某一个属性
     *
     * @param obj          bean
     * @param propertyName 属性名称
     * @return ValidResult
     */
    public static <T> ValidResult validateProperty(T obj, String propertyName) {
        ValidResult result = new ValidResult();
        Set<ConstraintViolation<T>> violationSet = validator.validateProperty(obj, propertyName);
        boolean hasError = violationSet != null && violationSet.size() > 0;
        result.setHasErrors(hasError);
        if (hasError) {
            for (ConstraintViolation<T> violation : violationSet) {
                result.addError(propertyName, violation.getMessage());
            }
        }
        return result;
    }
}

2. ValidResult 校验结果类

import java.util.ArrayList;
import java.util.List;

public class ValidResult {

    /**
     * 是否有错误
     */
    private boolean hasErrors;

    /**
     * 错误信息
     */
    private final List<ValidErrorMessage> errors;

    public ValidResult() {
        this.errors = new ArrayList<>();
    }
    public boolean hasErrors() {
        return hasErrors;
    }

    public void setHasErrors(boolean hasErrors) {
        this.hasErrors = hasErrors;
    }

    /**
     * 获取所有验证信息
     * @return 集合形式
     */
    public List<ValidErrorMessage> getAllErrors() {
        return errors;
    }
    /**
     * 获取所有验证信息
     * @return 字符串形式
     */
    public String getErrors(){
        StringBuilder sb = new StringBuilder();
        for (ValidErrorMessage error : errors) {
            sb.append(error.getPropertyPath()).append(":").append(error.getMessage()).append(" ");
        }
        return sb.toString();
    }

    public void addError(String propertyName, String message) {
        this.errors.add(new ValidErrorMessage(propertyName, message));
    }
}

3. 错误类

public class ValidErrorMessage {
    private String propertyPath;

    private String message;

    public String getPropertyPath() {
        return propertyPath;
    }

    public void setPropertyPath(String propertyPath) {
        this.propertyPath = propertyPath;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public ValidErrorMessage() {
    }

    public ValidErrorMessage(String propertyPath, String message) {
        this.propertyPath = propertyPath;
        this.message = message;
    }
}

4. 校验类

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;

public class CheckDataUpdateTimeJson {
    @NotBlank(message = "token不能为空!")
    private String token;
    
    public void setToken(String token) {
        this.token = token;
    }
    public String getToken() {
        return token;
    }
}

5. 使用

String requestJson = HelperUtils.convertStreamToString(request.getInputStream());
            CheckDataUpdateTimeJson paramJson = JSON.parseObject(requestJson, CheckDataUpdateTimeJson.class);
            ValidResult validResult = ValidatorUtil.validateBean(paramJson);
            if (validResult.hasErrors()) {
                System.out.println(validResult.getErrors());
            }

Spring 添加 Hibernate Validator支持 Add a provider like Hibernate Validator (RI) to your classpath

  1. 添加依赖
<dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.1.2.Final</version>
        </dependency>
<dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>
<dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator-annotation-processor</artifactId>
            <version>6.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator-cdi</artifactId>
            <version>6.1.2.Final</version>
        </dependency>
<dependency>
            <groupId>jakarta.validation</groupId>
            <artifactId>jakarta.validation-api</artifactId>
            <version>2.0.2</version>
        </dependency>
<dependency>
            <groupId>org.jboss.logging</groupId>
            <artifactId>jboss-logging</artifactId>
            <version>3.4.1.Final</version>
        </dependency>
<dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>jakarta.el</artifactId>
            <version>3.0.3</version>
        </dependency>
<dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>8.0.1</version>
            <scope>provided</scope>
        </dependency>

2. 向容器里注册一个处理器:

@Configuration
@EnableWebMvc
public class WebRootConfig {

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        return new MethodValidationPostProcessor();
    }
}

3. 增加验证类

public class AppLoginParam {
    @NotNull(message = "userName不能为空")
    private String userName;
    @NotNull(message = "password不能为空")
    private String password;
    
    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

4. Controller增加验证

    @RequestMapping("/login")
    @ResponseBody
    public AjaxJson login(@Valid @RequestBody AppLoginParam requestParam, BindingResult bindingResult) {
        AjaxJson res = new AjaxJson();
        Integer code = response.getStatus();
        res.setCode(String.valueOf(code));
        res.setStatus(false);
        // validator 验证
        if (bindingResult.hasErrors()) {
            res.setMessage(bindingResult.getFieldError().getDefaultMessage());
            return res;
        }
// do something....
}

cannot read realtime clock: Invalid argument

wsl ubuntu 20.04出现此问题

解决方法:

sudo -i
sudo mv /bin/sleep /bin/sleep~ ; touch /bin/sleep ; chmod +x /bin/sleep

或者:
wget https://launchpad.net/~rafaeldtinoco/+archive/ubuntu/lp1871129/+files/libc6_2.31-0ubuntu8+lp1871129~1_amd64.deb
sudo dpkg --install libc6_2.31-0ubuntu8+lp1871129~1_amd64.deb
sudo apt-mark hold libc6
sudo apt --fix-broken install
sudo apt full-upgrade