Validator工具验证类,区分添加,删除,修改

1:pom.xml添加必要依赖

 <dependency>
     <groupId>javax.validation</groupId>
     <artifactId>validation-api</artifactId>
 </dependency>
 <dependency>
     <groupId>org.hibernate.validator</groupId>
     <artifactId>hibernate-validator</artifactId>
     <version>6.2.4.Final</version>
 </dependency>

2:ValidatorUtils验证工具类

package com.example.clickhouse.util;

import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.MessageSourceResourceBundleLocator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Locale;
import java.util.Set;

/**
 * hibernate-validator 校验工具类
 *
 * @Author xu
 * @Date 2024/02/21
 */
public class ValidatorUtils {


    private static ResourceBundleMessageSource getMessageSource() {
        ResourceBundleMessageSource bundleMessageSource = new ResourceBundleMessageSource();
        bundleMessageSource.setDefaultEncoding("UTF-8");
        bundleMessageSource.setBasenames("i18n/validation", "i18n/validation_common");
        return bundleMessageSource;
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     */
    public static void validateEntity(Object object, Class<?>... groups) {
        Locale.setDefault(LocaleContextHolder.getLocale());
        Validator validator = Validation.byDefaultProvider().configure().messageInterpolator(new ResourceBundleMessageInterpolator(new MessageSourceResourceBundleLocator(getMessageSource()))).buildValidatorFactory().getValidator();
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            ConstraintViolation<Object> constraint = constraintViolations.iterator().next();
            throw new RuntimeException(constraint.getMessage());
        }
    }

}

3:添加注解,编辑注解

public interface AddGroup {
}
public interface EditGroup {
}

4:User实体类例子

@Data
public class User {

    @Null(message = "必须为空" ,groups = AddGroup.class)
    @NotBlank(message = "不可为空 ",groups = EditGroup.class)
    private String name;

    private String code;

    private String phone;
}

5:controller层验证

@GetMapping("/getList")
public List<UserInfo> getList(User user) {
    //ValidatorUtils.validateEntity(user, EditGroup.class);
    ValidatorUtils.validateEntity(user, AddGroup.class);
    return userInfoService.selectList();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值