后端表情包依赖+自定义注解实现校验

开发过程中遇到小程序登记信息填写文本时可能输入表情包,需要后端校验

由于字段太多,所以用自定义注解的方式来实现

步骤1:在pom文件中加入表情包依赖

        
            com.vdurmont
            emoji-java
            5.1.1
        

步骤2:

自定义注解类

package com.company.web.compatibility.annotation;

import cn.hutool.extra.emoji.EmojiUtil;
import com.itextpdf.text.log.SysoCounter;
import com.xiaoleilu.hutool.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
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 java.util.regex.Matcher;
import java.util.regex.Pattern;

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

/**
 * 

* 表情包自定义校验注解 *

* @date 2023/7/12/ */ @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = NotBlankEmoji.EmojiValidator.class) @Documented public @interface NotBlankEmoji { String message() default "不允许输入表情符号"; Class[] groups() default {}; Class[] payload() default {}; class EmojiValidator implements ConstraintValidator { @Override public void initialize(NotBlankEmoji constraintAnnotation) { } @Override public boolean isValid(String value, ConstraintValidatorContext context) { return !containsEmoji(value); } public boolean containsEmoji(String value) { if (StrUtil.isBlank(value)) { return false; } boolean emoji = EmojiUtil.containsEmoji(value); return emoji; } } }

步骤3:

在请求的实体使用这个注解,需要要在controller中加入@Validated注解,校验才会生效

@ApiModel("Hr结构人员教育经历")
@Data
public class HrWorkExperienceDto {
    @ApiModelProperty("证明人")
    @NotBlank(message = "证明人不能为空" )
    @Length(max=44, message = "证明人超过了44个字符" )
    @Xss( message = "证明人不能输入html特殊字符" )
    @NotBlankEmoji( message = "证明人不允许输入表情符号" )
    private String certifier;

}

你可能感兴趣的:(Java后的开发,java,spring,spring,boot)