自定义hibernate validator注解对字段进行校验

本文介绍了如何在web项目中利用Hibernate Validator创建自定义注解,以实现用户存在性的校验。通过在controller接口参数上添加自定义的@UserField注解,可以在多个地方复用该校验逻辑,简化代码并提高代码的可维护性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.  hibernate validator注解在web项目中经常用到,是一个很好用的字段校验器,可以对前端传入的参数进行判断,如是否为空,是否满足正则规定的格式等等。

2. 假设有一个业务场景,需要判断前端传入的用户是否存在,而项目中有很多地方会用到此判断,此时可以构造一个自定义校验器进行字段校验,在需要的时候只需要加上此注解即可。

3. controller接口

package net.mshome.twisted.tmall.common.controller;


import net.mshome.twisted.tmall.common.dto.UserAddDTO;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tangjizhou
 * @since 2019-05-04
 */
@RestController
@RequestMapping("/user")
@Validated
public class UserController {


    @PostMapping("/register")
    public void register(@RequestBody @Valid UserAddDTO userAddDTO) {

    }

}

4. 前端传入的参数,注意此处的自定义注解 @UserField

package net.mshome.twisted.tmall.common.dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import net.mshome.twisted.tmall.common.annotation.UserField;

import javax.validation.constraints.NotNull;

/**
 * @author tangjizhou
 * @date 2019-06-20
 * @description 前端post传入参数
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserAddDTO {

    /**
     * 假设此处可填写多个用户,以逗号隔开
     */
    @UserField(message = "填写的用户{}不存在")
    @NotNull(message = "请填写用户")
    private String usernames;

}

5. 自定义注解

package net.mshome.twisted.tmall.common.annotation;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;

/**
 * @author tangjizhou
 * @date 2019-06-20
 * @description 验证用户是否存在注解
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Constraint(validatedBy = UserFieldValidator.class)
public @interface UserField {

    String message() default "";

    String defaultMessage = "用户{}不存在";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}

6. 实现注解功能

package net.mshome.twisted.tmall.common.annotation;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.mshome.twisted.tmall.common.entity.User;
import net.mshome.twisted.tmall.common.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @author tangjizhou
 * @date 2019-06-20
 * @description 验证用户是否存在
 */
@Component
public class UserFieldValidator implements ConstraintValidator<UserField, String> {

    private String defaultMessage;

    @Autowired
    private IUserService userService;

    @Override
    public void initialize(UserField constraint) {
        this.defaultMessage = constraint.defaultMessage;
    }

    @Override
    public boolean isValid(String usernames, ConstraintValidatorContext context) {

        // 如果什么都没有输入,则不判断,直接返回
        if (StringUtils.isEmpty(usernames)) {
            return true;
        }

        // 判断用户是否存在
        String illegalUsernames = Arrays.stream(usernames.split(",")).distinct().map(username -> {
            int count = userService.count(new QueryWrapper<>(User.builder().username(username).build()));
            return count == 0 ? username : null;
        }).filter(StringUtils::isNotEmpty).collect(Collectors.joining(","));

        // 所有用户都存在,返回true
        if (StringUtils.isBlank(illegalUsernames)) {
            return true;
        }

        /* ************************ 如果存在非法用户****************************/

        // 禁用直接返回默认的message
        context.disableDefaultConstraintViolation();

        // 获取注解配置的message
        String messageTemplate = context.getDefaultConstraintMessageTemplate();
        messageTemplate = StringUtils.isEmpty(messageTemplate) ? defaultMessage : messageTemplate;

        // 构造返回信息,进行占位符替换
        context.buildConstraintViolationWithTemplate(StringUtils.replace(messageTemplate, "{}", illegalUsernames))
                .addConstraintViolation();

        return false;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值