文章目錄
- DateUtils
- EncryptUtils
- Fun
- IdCardCalibrationUtil
- Result
- ResultCode
- ValidateNameUtil
- ValidatePhoneUtil
廢話少說看源碼
DateUtils
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
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
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
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
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
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
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
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();}
}