Background verification

Background validation framework BeanValidate

One. Import the following dependencies in Maven
  <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.0.13.Final</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>6.0.13.Final</version>
    </dependency>
two. Add the following configuration in spring-context
<bean id="validator"  class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
    <bean id="beanValidator" class="com.twgfs.commons.utils.BeanValidator">
        <property name="validator" ref="validator" />
    </bean>

Note: aboveThe com.twgfs.commons.utils.BeanValidator behind the class inside is the location of the Java verification package

three. Writing verification
package com.twgfs.commons.utils;

import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import java.util.*;

public class BeanValidator {
    @Autowired
    private static Validator validator;

    public static void setValidator(Validator validator) {
        BeanValidator.validator = validator;
    }

    /**
     *调用 JSR303 的 validate 方法, 验证失败时抛出 ConstraintViolationException.
     */
    private static void validateWithException(Validator validator, Object object, Class<?>... groups) throws ConstraintViolationException {
        Set constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            throw new ConstraintViolationException(constraintViolations);
        }
    }


     /*辅助方法, 转换 ConstraintViolationException 中的 Set<ConstraintViolations> 中为 List<message>.*/

    private static List<String> extractMessage(ConstraintViolationException e) {
        return extractMessage(e.getConstraintViolations());
    }


      /*辅助方法, 转换 Set<ConstraintViolation> 为 List<message>*/

    private static List<String> extractMessage(Set<? extends ConstraintViolation> constraintViolations) {
        List<String> errorMessages = new ArrayList<>();
        for (ConstraintViolation violation : constraintViolations) {
            errorMessages.add(violation.getMessage());
        }
        return errorMessages;
    }

    //辅助方法, 转换 ConstraintViolationException 中的 Set<ConstraintViolations> 为 Map<property, message>.

    private static Map<String, String> extractPropertyAndMessage(ConstraintViolationException e) {
        return extractPropertyAndMessage(e.getConstraintViolations());
    }

    //辅助方法, 转换 Set<ConstraintViolation> 为 Map<property, message>.

    private static Map<String, String> extractPropertyAndMessage(Set<? extends ConstraintViolation> constraintViolations) {
        Map<String, String> errorMessages = new HashMap<>();
        for (ConstraintViolation violation : constraintViolations) {
            errorMessages.put(violation.getPropertyPath().toString(), violation.getMessage());
        }
        return errorMessages;
    }


    //辅助方法, 转换 ConstraintViolationException 中的 Set<ConstraintViolations> 为 List<propertyPath message>.

    private static List<String> extractPropertyAndMessageAsList(ConstraintViolationException e) {
        return extractPropertyAndMessageAsList(e.getConstraintViolations(), " ");
    }

//辅助方法, 转换 Set<ConstraintViolations> 为 List<propertyPath message>.

    private static List<String> extractPropertyAndMessageAsList(Set<? extends ConstraintViolation> constraintViolations) {
        return extractPropertyAndMessageAsList(constraintViolations, " ");
    }

//辅助方法, 转换 ConstraintViolationException 中的 Set<ConstraintViolations> 为 List<propertyPath + separator + message>.

    private static List<String> extractPropertyAndMessageAsList(ConstraintViolationException e, String separator) {
        return extractPropertyAndMessageAsList(e.getConstraintViolations(), separator);
    }

    //辅助方法, 转换 Set<ConstraintViolation> 为 List<propertyPath + separator + message>.

    private static List<String> extractPropertyAndMessageAsList(Set<? extends ConstraintViolation> constraintViolations, String separator) {
        List<String> errorMessages = new ArrayList<>();
        for (ConstraintViolation violation : constraintViolations) {
            errorMessages.add(violation.getPropertyPath() + separator + violation.getMessage());
        }
        return errorMessages;
    }
    /**
     * 服务端参数有效性验证
     *
     * @param object 验证的实体对象
     * @param groups 验证组
     * @return 验证成功:返回 null;验证失败:返回错误信息
     */
    public static String validator(Object object, Class<?>... groups) {
        try {
            validateWithException(validator, object, groups);
        } catch (ConstraintViolationException ex) {
            List<String> list = extractMessage(ex);
            list.add(0, "注意:");

            // 封装错误消息为字符串
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.size(); i++) {
                String exMsg = list.get(i);
                if (i != 0 ){
                    sb.append(String.format("%s. %s", i, exMsg)).append(list.size() > 1 ? "&nbsp;&nbsp;" : "");
                } else {
                    sb.append(exMsg).append(list.size() > 1 ? "&nbsp;&nbsp;" : "");
                }
            }
            return sb.toString();
        }
        return null;
    }
}

Note: This class is an exception catching class, a method is added at the end of the class as follows

public static String validator(Object object, Class<?>... groups) {
        try {
            validateWithException(validator, object, groups);
        } catch (ConstraintViolationException ex) {
            List<String> list = extractMessage(ex);
            list.add(0, "注意:");

            // 封装错误消息为字符串
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.size(); i++) {
                String exMsg = list.get(i);
                if (i != 0 ){
                    sb.append(String.format("%s. %s", i, exMsg)).append(list.size() > 1 ? "&nbsp;&nbsp;" : "");
                } else {
                    sb.append(exMsg).append(list.size() > 1 ? "&nbsp;&nbsp;" : "");
                }
            }
            return sb.toString();//返回自己写的错误提示信息
        }
        return null;
    }

This is used to capture the verification error and then output the corresponding error information. This method will output the information in the annotation according to your annotation on the entity class.

four. Add the corresponding annotations to the fields that need to be verified in the background of the entity class. The following is my entity class.
package com.twgfs.domain.entity;
import com.twgfs.commons.utils.RegexpUtils;
import lombok.Data;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;

@Data
public class User {
  private Integer id;
 @NotEmpty(message = "用户名不能为空")
  private String username;
  @NotEmpty(message = "密码不能为空")
  private String password;
  @NotEmpty(message = "电话号码不能为空")
  @Pattern(regexp = RegexpUtils.PHONE, message = "手机格式不正确")
  private String phone;
  @NotEmpty(message = "邮箱不能为空")
  @Pattern(regexp = RegexpUtils.EMAIL, message = "邮箱格式不正确")
  private String email;
  //数据库ORM会忽略该字段
//  @Transient
//  public int totalPage;

}

1. The above @NotEmpty is a non-empty verification in Validate. If you add a message = "XXXXX" in the main, it will be verified when the input value is empty. If it is empty, then an error will be reported. Write the verification class to capture and get the corresponding value. If you need to perform regular verification, you can add @Pattern (regexp = RegexpUtils.EMAIL, message = "mailbox format is incorrect") to the corresponding field that needs to be verified. , But here RegexpUtils.EMAIL is a field in the regular class to be matched, the matched regular class is as follows

package com.twgfs.commons.utils;

public class RegexpUtils {
    /**
     * 验证手机号
     */
    public static final String PHONE = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";

    /**
     * 验证邮箱地址
     */
    public static final String EMAIL = "\\w+(\\.\\w)*@\\w+(\\.\\w{2,3}){1,3}";

    /**
     * 验证手机号
     * @param phone
     * @return
     */
    public static boolean checkPhone(String phone) {
        return phone.matches(PHONE);
    }

    /**
     * 验证邮箱
     * @param email
     * @return
     */
    public static boolean checkEmail(String email) {
        return email.matches(EMAIL);
    }
}

Five. After a series of these preparations, it can be used in the project, here is a non-empty verification of my registration module for example.
@RequestMapping("/regist")
    public String regist(User user, Model model){
        String result = BeanValidator.validator(user);
        int flag = loginRegistService.ToRegist(user);
        model.addAttribute("validatemsg",result);
        System.out.println(result+"=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
        return "index";
    }
  1. Here String result = BeanValidator.validator (user); is to apply validation to the project
  2. Put the entity mapping class user registered in the foreground into BeanValidator.validator (user) to complete the background verification
  3. The entity class of the background verification is verified according to the annotation. If a mismatch is found, an error will be reported, and then the error will be captured by the verification class written to be output one by one according to the class content in the message on the entity class The result printed here is mismatched
Published 19 original articles · praised 7 · views 6633

Guess you like

Origin blog.csdn.net/William_TWG/article/details/85235932