文章目录
- DateUtils
- EncryptUtils
- Fun
- IdCardCalibrationUtil
- Result
- ResultCode
- ValidateNameUtil
- ValidatePhoneUtil
废话少说看源码
DateUtils
java">package com.huihang.core.utils;import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;public class DateUtils {private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");// 其他方法.../*** 获得当前日期 yyyy-MM-dd HH:mm:ss*/public String getCurrentTime() {return LocalDateTime.now().format(DATE_TIME_FORMATTER);}/*** 获取系统当前时间戳*/public String getSystemTime() {return String.valueOf(System.currentTimeMillis());}/*** 获取当前日期 yyyy-MM-dd*/public String getDateByString() {return LocalDate.now().format(DATE_FORMATTER);}/*** 得到两个时间差 格式yyyy-MM-dd HH:mm:ss*/public long dateSubtraction(String start, String end) {LocalDateTime startDate = LocalDateTime.parse(start, DATE_TIME_FORMATTER);LocalDateTime endDate = LocalDateTime.parse(end, DATE_TIME_FORMATTER);return Duration.between(startDate, endDate).toMillis();}/*** 判断当前时间是否在[startTime, endTime]区间*/public boolean isEffectiveDate(LocalDate nowTime, String dateSection) {String[] times = dateSection.split(",");LocalDate startTime = LocalDate.parse(times[0], DATE_FORMATTER);LocalDate endTime = LocalDate.parse(times[1], DATE_FORMATTER);return !nowTime.isBefore(startTime) && !nowTime.isAfter(endTime);}}
EncryptUtils
java">package com.huihang.core.utils;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Base64;public class EncryptUtils {private static final String AES_MODE = "AES/GCM/NoPadding";private static final int GCM_TAG_LENGTH = 128;private static final int AES_KEY_SIZE = 32; // 32字节 = 256位密钥private static final int GCM_IV_SIZE = 12; // GCM模式下通常使用12字节IV// 定义固定的密钥和IVprivate static final byte[] FIXED_KEY = new byte[]{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xAA, (byte) 0xBB, (byte)0xCC, (byte)0xDD, (byte)0xEE, (byte)0xFF, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte)0x88,(byte) 0x99, (byte)0xAA, (byte)0xBB,(byte) 0xCC, (byte)0xDD, (byte)0xEE,(byte) 0xFF};private static final byte[] FIXED_IV = new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B};private static final SecretKey key = new SecretKeySpec(FIXED_KEY, "AES");private static final byte[] iv = FIXED_IV;/*** 使用提供的 AES 密钥和初始化向量(IV)对数据进行加密。** @param data 要加密的数据* @return 返回 Base64 编码的加密结果*/public static String aesEncrypt(String data) {try {Cipher cipher = Cipher.getInstance(AES_MODE);GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);cipher.init(Cipher.ENCRYPT_MODE, key, spec);byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));return Base64.getEncoder().encodeToString(encrypted);} catch (Exception e) {throw new RuntimeException(e);}}/*** 使用提供的 AES 密钥和初始化向量(IV)对加密的数据进行解密。** @param encryptedData Base64 编码的加密数据* @return 返回解密后的原始数据*/public static String aesDecrypt(String encryptedData) {try {Cipher cipher = Cipher.getInstance(AES_MODE);GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);cipher.init(Cipher.DECRYPT_MODE, key, spec);byte[] decoded = Base64.getDecoder().decode(encryptedData);byte[] decrypted = cipher.doFinal(decoded);return new String(decrypted, StandardCharsets.UTF_8);} catch (Exception e) {throw new RuntimeException(e);}}/*** 生成一个指定长度的随机密钥。** @return 生成的AES密钥*/private static SecretKey generateAESKey() {byte[] keyBytes = new byte[AES_KEY_SIZE];SecureRandom random = new SecureRandom();random.nextBytes(keyBytes);return new SecretKeySpec(keyBytes, "AES");}/*** 生成一个指定长度的随机IV。** @return 生成的IV字节数组*/private static byte[] generateIV() {byte[] iv = new byte[GCM_IV_SIZE];SecureRandom random = new SecureRandom();random.nextBytes(iv);return iv;}/*** 对输入字符串进行 MD5 哈希计算。** @param data 要哈希的字符串* @return 返回 32 位十六进制表示的 MD5 哈希值* @throws NoSuchAlgorithmException 如果无法获取指定算法的消息摘要实例*/public static String md5(String data){MessageDigest md = null;try {md = MessageDigest.getInstance("MD5");} catch (NoSuchAlgorithmException e) {throw new RuntimeException(e);}byte[] digest = md.digest(data.getBytes(StandardCharsets.UTF_8));return bytesToHex(digest);}/*** 对输入字符串进行 SHA-256 哈希计算。** @param data 要哈希的字符串* @return 返回 64 位十六进制表示的 SHA-256 哈希值* @throws NoSuchAlgorithmException 如果无法获取指定算法的消息摘要实例*/public static String sha256(String data) throws NoSuchAlgorithmException {MessageDigest md = MessageDigest.getInstance("SHA-256");byte[] digest = md.digest(data.getBytes(StandardCharsets.UTF_8));return bytesToHex(digest);}/*** 使用提供的 AES 密钥和初始化向量(IV)对数据进行加密。** @param data 要加密的数据* @param key AES 加密密钥* @param iv 初始化向量,对于 GCM 模式应为 12 字节* @return 返回 Base64 编码的加密结果* @throws Exception 如果加密过程中出现错误*/public static String aesEncrypt(String data, SecretKey key, byte[] iv) {Cipher cipher = null;try {cipher = Cipher.getInstance(AES_MODE);GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);cipher.init(Cipher.ENCRYPT_MODE, key, spec);byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));return Base64.getEncoder().encodeToString(encrypted);} catch (Exception e) {throw new RuntimeException(e);}}/*** 使用提供的 AES 密钥和初始化向量(IV)对加密的数据进行解密。** @param encryptedData Base64 编码的加密数据* @param key AES 解密密钥* @param iv 初始化向量,对于 GCM 模式应为 12 字节* @return 返回解密后的原始数据* @throws Exception 如果解密过程中出现错误*/public static String aesDecrypt(String encryptedData, SecretKey key, byte[] iv) {Cipher cipher = null;try {cipher = Cipher.getInstance(AES_MODE);GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);cipher.init(Cipher.DECRYPT_MODE, key, spec);byte[] decoded = Base64.getDecoder().decode(encryptedData);byte[] decrypted = cipher.doFinal(decoded);return new String(decrypted, StandardCharsets.UTF_8);} catch (Exception e) {throw new RuntimeException(e);}}/*** 使用 RSA 公钥对数据进行加密。** @param data 要加密的数据* @param publicKey RSA 公钥* @return 返回 Base64 编码的加密结果* @throws Exception 如果加密过程中出现错误*/public static String rsaEncrypt(String data, PublicKey publicKey) throws Exception {Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");cipher.init(Cipher.ENCRYPT_MODE, publicKey);byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));return Base64.getEncoder().encodeToString(encrypted);}/*** 使用 RSA 私钥对加密的数据进行解密。** @param encryptedData Base64 编码的加密数据* @param privateKey RSA 私钥* @return 返回解密后的原始数据* @throws Exception 如果解密过程中出现错误*/public static String rsaDecrypt(String encryptedData, PrivateKey privateKey) throws Exception {Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");cipher.init(Cipher.DECRYPT_MODE, privateKey);byte[] decoded = Base64.getDecoder().decode(encryptedData);byte[] decrypted = cipher.doFinal(decoded);return new String(decrypted, StandardCharsets.UTF_8);}/*** 生成一个指定大小的 RSA 密钥对。** @param keySize RSA 密钥长度(例如 2048)* @return 返回生成的 KeyPair 对象,包含公钥和私钥* @throws NoSuchAlgorithmException 如果无法获取指定算法的密钥对生成器实例*/public static KeyPair generateRsaKeyPair(int keySize) throws NoSuchAlgorithmException {KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");keyGen.initialize(keySize);return keyGen.generateKeyPair();}/*** 生成一个新的 AES 密钥。** @return 返回生成的 AES SecretKey 对象* @throws NoSuchAlgorithmException 如果无法获取指定算法的密钥生成器实例*/public static SecretKey generateAesKey() throws NoSuchAlgorithmException {KeyGenerator keyGen = KeyGenerator.getInstance("AES");keyGen.init(AES_KEY_SIZE);return keyGen.generateKey();}/*** 将字节数组转换为十六进制字符串。** @param bytes 要转换的字节数组* @return 返回对应的十六进制字符串*/private static String bytesToHex(byte[] bytes) {StringBuilder sb = new StringBuilder();for (byte b : bytes) {sb.append(String.format("%02x", b));}return sb.toString();}
}
Fun
java">package com.huihang.core.utils;import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.*;public class Fun {/*** 检查给定的集合是否为空或null。** @param collection 要检查的集合* @return 如果集合是null或空,则返回true;否则返回false。*/public static boolean isEmpty(Collection<?> collection) {return (collection == null || collection.isEmpty());}/*** 检查给定的map是否为空或null。** @param map 要检查的map* @return 如果地图是null或空,则返回true;否则返回false。*/public static boolean isEmpty(Map<?, ?> map) {return (map == null || map.isEmpty());}public static boolean isEmpty(Object o) {return Objects.isNull(o);}public static boolean isNotEmpty(Object o) {return Objects.nonNull(o);}/*** 检查给定的集合是否不为空且非null。** @param collection 要检查的集合* @return 如果集合不是null并且包含元素,则返回true;否则返回false。*/public static boolean isNotEmpty(Collection<?> collection) {return (collection != null && !collection.isEmpty());}/*** 检查给定的地图是否不为空且非null。** @param map 要检查的地图* @return 如果地图不是null并且包含条目,则返回true;否则返回false。*/public static boolean isNotEmpty(Map<?, ?> map) {return (map != null && !map.isEmpty());}/*** 检查给定的CharSequence对象是否为空字符串或null。** @param cs 要检查的CharSequence对象(如String)* @return 如果CharSequence是null或长度为0,则返回true;否则返回false。*/public static boolean isEmpty(CharSequence cs) {return cs == null || cs.isEmpty();}/*** 检查给定的CharSequence对象是否不为空字符串且非null。** @param cs 要检查的CharSequence对象(如String)* @return 如果CharSequence不是null并且长度大于0,则返回true;否则返回false。*/public static boolean isNotEmpty(CharSequence cs) {return !isEmpty(cs);}/*** 拷贝数据到新对象(单个)** @param source 源实例对象* @return 拷贝后的新实例对象*/public static <T> T copy(T source) {if (Objects.isNull(source)) {return null;}Class<?> c = source.getClass();List<Field> fields = getFields(c);return newInstance(source, c, fields);}/*** 拷贝数据到新对象(批量)** @param sourceList 源实例对象集合* @return 拷贝后的新实例对象集合*/public static <T> List<T> copyList(List<T> sourceList) {if (Objects.isNull(sourceList) || sourceList.isEmpty()) {return Collections.emptyList();}Class<?> c = getClass(sourceList);if (Objects.isNull(c)) {return Collections.emptyList();}List<Field> fields = getFields(c);List<T> ts = new ArrayList<>();for (T t : sourceList) {T s = newInstance(t, c, fields);if (Objects.nonNull(s)) {ts.add(s);}}return ts;}/*** 单个深度拷贝** @param source 源实例化对象* @param target 目标对象类(如:User.class)* @return 目标实例化对象*/public static <T> T copy(Object source, Class<T> target) {if (Objects.isNull(source) || Objects.isNull(target)) {return null;}List<Field> sourceFields = getFields(source.getClass());List<Field> targetFields = getFields(target);T t = null;try {t = newInstance(source, target, sourceFields, targetFields);} catch (Exception e) {e.printStackTrace();}return t;}/*** 批量深度拷贝(如果原集合中有null,则自动忽略)** @param sourceList 源实例化对象集合* @param target 目标对象类(如:User.class)* @return 目标实例化对象集合*/public static <T, K> List<K> copyList(List<T> sourceList, Class<K> target) {if (Objects.isNull(sourceList) || sourceList.isEmpty() || Objects.isNull(target)) {return Collections.emptyList();}Class<?> c = getClass(sourceList);if (Objects.isNull(c)) {return Collections.emptyList();}List<Field> sourceFields = getFields(c);List<Field> targetFields = getFields(target);List<K> ks = new ArrayList<>();for (T t : sourceList) {if (Objects.nonNull(t)) {try {K k = newInstance(t, target, sourceFields, targetFields);ks.add(k);} catch (Exception e) {e.printStackTrace();}}}return ks;}/*** 获取List集合中的类名** @param list 对象集合* @return 类名*/private static <T> Class<?> getClass(List<T> list) {for (T t : list) {if (Objects.nonNull(t)) {return t.getClass();}}return null;}/*** 实例化同源对象** @param source 源对象* @param c 源对象类名* @param fields 源对象属性集合* @return 同源新对象*/@SuppressWarnings("unchecked")private static <T> T newInstance(T source, Class<?> c, List<Field> fields) {T t = null;try {t = (T) c.newInstance();for (Field field : fields) {field.setAccessible(true);field.set(t, field.get(source));}} catch (Exception e) {e.printStackTrace();}return t;}/*** 目标实例化对象** @param source 原对实例化象* @param target 目标对象类* @param sourceFields 源对象字段集合* @param targetFields 目标对象属性字段集合* @return 目标实例化对象*/private static <T> T newInstance(Object source, Class<T> target, List<Field> sourceFields,List<Field> targetFields) throws Exception {Constructor<T> constructor = target.getDeclaredConstructor();T t = constructor.newInstance();if (targetFields.isEmpty()) {return t;}for (Field field : sourceFields) {field.setAccessible(true);Object o = field.get(source);Field sameField = getSameField(field, targetFields);if (Objects.nonNull(sameField)) {sameField.setAccessible(true);sameField.set(t, o);}}return t;}/*** 获取目标对象中同源对象属性相同的属性(字段名称,字段类型一致则判定为相同)** @param field 源对象属性* @param fields 目标对象属性集合* @return 目标对象相同的属性*/private static Field getSameField(Field field, List<Field> fields) {String name = field.getName();String type = field.getType().getName();for (Field f : fields) {if (name.equals(f.getName()) && type.equals(f.getType().getName())) {return f;}}return null;}/*** 获取一个类中的所有属性(包括父类属性)** @param c 类名* @return List<Field>*/private static List<Field> getFields(Class<?> c) {List<Field> fieldList = new ArrayList<>();Field[] fields = c.getDeclaredFields();if (fields.length > 0) {fieldList.addAll(Arrays.asList(fields));}return getSuperClassFields(c, fieldList);}/*** 递归获取父类属性** @param o 类名* @param allFields 外层定义的所有属性集合* @return 父类所有属性*/private static List<Field> getSuperClassFields(Class<?> o, List<Field> allFields) {Class<?> superclass = o.getSuperclass();if (Objects.isNull(superclass) || Object.class.getName().equals(superclass.getName())) {return allFields;}Field[] fields = superclass.getDeclaredFields();if (fields.length == 0) {return allFields;}allFields.addAll(Arrays.asList(fields));return getSuperClassFields(superclass, allFields);}}
IdCardCalibrationUtil
java">package com.huihang.core.utils;import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.stream.IntStream;/*** 身份证校准工具*/
public class IdCardCalibrationUtil {private static final List<Integer> FACTORS = List.of(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);private static final String[] VERIFY_CODES = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");public static boolean validateIdCard(String idCard) {return switch (idCard.length()) {case 18 -> validate18DigitIdCard(idCard);case 15 -> validateConverted15DigitIdCard(idCard);default -> false;};}private static boolean validate18DigitIdCard(String idCard) {var sum = IntStream.range(0, 17).map(i -> Character.getNumericValue(idCard.charAt(i)) * FACTORS.get(i)).sum();var mod = sum % 11;return VERIFY_CODES[mod].equalsIgnoreCase(idCard.substring(17));}private static boolean validateConverted15DigitIdCard(String idCard) {if (!idCard.matches("\\d{15}")) {return false;}try {String newBirthDate = "19" + idCard.substring(6, 8) + idCard.substring(6, 12);LocalDate.parse(newBirthDate, DATE_FORMATTER);String newIdCard = idCard.substring(0, 6) + newBirthDate + idCard.substring(12, 15);String checkSum = calculateCheckSum(newIdCard);return validate18DigitIdCard(newIdCard + checkSum);} catch (DateTimeParseException e) {return false;}}private static String calculateCheckSum(String idCard) {var sum = IntStream.range(0, 17).map(i -> Character.getNumericValue(idCard.charAt(i)) * FACTORS.get(i)).sum();int mod = sum % 11;return VERIFY_CODES[mod];}
}
Result
java">package com.huihang.core.utils;import lombok.AllArgsConstructor;
import lombok.Data;@Data
@AllArgsConstructor
public class Result<T> {private Integer code; //状态码private String message; //返回信息private T data; //返回数据public static <T> Result<T> success(T data) {return new Result<>(ResultCode.SUCCESS.getCode(),ResultCode.SUCCESS.getMessage(), data);}public static <T> Result<T> error(int resultCode) {return new Result<>(resultCode, ResultCode.getMessageByCode(resultCode), null);}
}
ResultCode
java">package com.huihang.core.utils;
import lombok.Getter;
@Getter
public enum ResultCode {SUCCESS(2000, "成功"),RESOURCE_UPDATED(2001, "资源更新成功"),RESOURCE_DELETED(2002, "资源删除成功"),BATCH_OPERATION_SUCCESS(2003, "批量操作成功"),ASYNCHRONOUS_PROCESS_STARTED(2004, "异步处理已开始"),DATA_PROCESSED(2005, "数据处理成功"),SUBSCRIPTION_CREATED(2006, "订阅创建成功"),USER_ACTIVATED(2007, "用户激活成功"),PASSWORD_RESET(2008, "密码重置成功"),EMAIL_VERIFIED(2009, "邮箱验证成功"),SMS_VERIFIED(2011, "短信验证成功"),LICENSE_GRANTED(2012, "授权许可已授予"),TRANSACTION_COMMITTED(2013, "事务提交成功"),CACHE_CLEARED(2014, "缓存清除成功"),CONFIGURATION_SAVED(2015, "配置保存成功"),EXPORT_COMPLETED(2016, "导出完成"),IMPORT_COMPLETED(2017, "导入完成"),PAYMENT_RECEIVED(2018, "支付已接收"),REFUND_COMPLETED(2019, "退款完成"),TASK_COMPLETED(2020, "任务完成"),FILE_UPLOADED(2021, "文件上传成功"),FILE_DOWNLOADED(2022, "文件下载成功"),MESSAGE_SENT(2023, "消息发送成功"),NOTIFICATION_SENT(2024, "通知发送成功"),INVITATION_SENT(2025, "邀请发送成功"),ACCOUNT_LOCKED(2026, "账户锁定成功"),ACCOUNT_UNLOCKED(2027, "账户解锁成功"),SESSION_CREATED(2028, "会话创建成功"),SESSION_TERMINATED(2029, "会话终止成功"),TOKEN_GENERATED(2030, "令牌生成成功"),API_KEY_GENERATED(2031, "API密钥生成成功"),INCORRECT_PARAM(4010, "参数不正确"),VALIDATION_ERROR(4000, "数据验证错误"),VERSION_MISMATCH(4002, "版本不匹配"),DEPRECATED_API(4003, "已废弃的API接口"),ILLEGAL_OPERATION(4004, "非法操作"),DATA_FORMAT_ERROR(4005, "数据格式错误"),QUOTA_EXCEEDED(4006, "超出配额限制"),VERIFICATION_FAILED(4007, "验证失败"),ENTITY_LOCKED(4008, "实体已被锁定"),UNPARSEABLE_CONTENT(4009, "无法解析的内容"),TOO_MANY_REQUESTS(4290, "请求过于频繁,请稍后再试"),UNSUPPORTED_MEDIA_TYPE(4150, "不支持的媒体类型"),REQUEST_ENTITY_TOO_LARGE(4130, "请求体过大"),METHOD_NOT_ALLOWED(4050, "方法不允许"),IP_NOT_ALLOWED(4031, "不允许的IP地址"),USER_NOT_EXISTS(4040, "用户不存在"),NOT_FOUND(4040, "资源未找到"),CAPTCHA_ERROR(4011, "验证码错误"),CAPTCHA_TOO_MANY_REQUESTS_ERROR(4012, "验证码请求次数过多,请稍后重试!"),CLIENT_CLOSED_REQUEST(4999, "客户端关闭连接"),ERROR(5000, "失败"),TIMEOUT(5004, "操作超时"),INTERNAL_ERROR(5008, "系统内部错误"),SERVICE_UNAVAILABLE(5003, "服务不可用"),DEPENDENCY_SERVICE_UNAVAILABLE(5009, "依赖的服务不可用"),THIRD_PARTY_SERVICE_ERROR(5013, "第三方服务响应异常"),TRANSACTION_FAILED(5014, "事务处理失败"),CACHE_OPERATION_FAILED(5015, "缓存操作失败"),ENCRYPTION_DECRYPTION_ERROR(5016, "数据加密解密失败"),DATA_SYNC_FAILED(5017, "数据同步失败"),EMAIL_SENDING_FAILED(5018, "邮件发送失败"),SMS_SENDING_FAILED(5019, "短信发送失败"),PAYMENT_FAILED(5020, "支付失败"),TASK_EXECUTION_FAILED(5021, "任务执行失败"),NETWORK_FAILURE(5011, "网络连接失败"),SERVER_CLOSED_CONNECTION(5010, "服务器关闭连接"),CONFIGURATION_ERROR(5012, "配置错误"),EXTERNAL_SERVICE_FAIL(5002, "外部服务调用失败"),NO_LOGIN(6000, "未登录"),FAIL_LOGIN(6001,"登录失败,账户或密码错误!"),ACCOUNT_LOCKOUT(6002,"账户已锁定"),AUTHENTICATION_FAILED(6003, "认证失败"),INVALID_TOKEN(6004, "令牌无效"),TOKEN_EXPIRED(6005, "令牌过期"),NO_AUTH(7000, "没有权限"),ACCESS_DENIED(7002, "禁止访问"),OPERATION_DENIED(7001, "操作被拒绝"),SESSION_EXPIRED(6001, "会话过期"),UPLOAD_FAIL(5005, "文件上传失败"),DOWNLOAD_FAIL(5006, "文件下载失败"),DATABASE_ERROR(5007, "数据库操作失败");private final int code;private final String message;ResultCode(int code, String message) {this.code = code;this.message = message;}public static String getMessageByCode(int code) {for (ResultCode resultCode : ResultCode.values()) {if (resultCode.getCode() == code) {return resultCode.getMessage();}}return null;}
}
ValidateNameUtil
java">package com.huihang.core.utils;import java.util.regex.Pattern;/*** 名称校验工具*/
public class ValidateNameUtil {// 定义两个正则表达式,一个用于汉字姓名,一个用于英文姓名private static final Pattern CHINESE_NAME_PATTERN = Pattern.compile("^[\\u4e00-\\u9fa5]{2,18}$");private static final Pattern ENGLISH_NAME_PATTERN = Pattern.compile("^[a-zA-Z\\s-]{2,80}$");/*** 验证输入的名字是否符合汉字或英文名字的格式.** @param name 待验证的名字字符串* @return 如果名字格式正确返回 true,否则返回 false*/public static boolean validateName(String name) {if (name == null || name.trim().isEmpty()) {return false;}// 检查是否为中文名字或英文名字return isValidChineseName(name) || isValidEnglishName(name);}/*** 验证输入的名字是否符合汉字姓名的格式.** @param name 待验证的名字字符串* @return 如果名字格式正确返回 true,否则返回 false*/public static boolean isValidChineseName(String name) {if (name == null || name.trim().isEmpty()) {return false;}return CHINESE_NAME_PATTERN.matcher(name).matches();}/*** 验证输入的名字是否符合英文姓名的格式.** @param name 待验证的名字字符串* @return 如果名字格式正确返回 true,否则返回 false*/public static boolean isValidEnglishName(String name) {if (name == null || name.trim().isEmpty()) {return false;}return ENGLISH_NAME_PATTERN.matcher(name).matches();}
}
ValidatePhoneUtil
java">package com.huihang.core.utils;import java.util.regex.Pattern;/*** 手机号校验工具*/
public class ValidatePhoneUtil {// 定义一个正则表达式来匹配中国大陆手机号private static final Pattern PHONE_NUMBER_PATTERN = Pattern.compile("^1(3[0-9]|4[579]|5[0-35-9]|6[6]|7[0135678]|8[0-9]|9[89])\\d{8}$");/*** 验证输入的字符串是否符合中国大陆手机号的格式.** @param phoneNumber 待验证的手机号字符串* @return 如果手机号格式正确返回 true,否则返回 false*/public static boolean validatePhoneNumber(String phoneNumber) {if (phoneNumber == null || phoneNumber.trim().isEmpty()) {return false;}// 使用预编译得正则表达式校验手机号码return PHONE_NUMBER_PATTERN.matcher(phoneNumber).matches();}
}