• 项目常用工具类


    Java本身自带了许多非常好用的工具类,但有时我们的业务千奇百怪,自带的工具类又无法满足业务需求,需要在这些工具类的基础上进行二次封装改造。以下是在实际工作中,可能会使用到的工具类。

    一、对象的序列化和反序列化

    对象的序列化和反序列化有很多方式,这里介绍一下最常用的Jackson

    Jackson 是一个简单基于 Java 应用库,Jackson 可以轻松的将 Java 对象转换成 json 对象和 xml 文档,同样也可以将 json、xml 转换成 Java 对象。并且Jackson是开源免费的,源代码托管在 GitHub 上。

    1.1 Jackson注解

    Jackson 类库包含了很多注解,可以让我们快速建立 Java 类与 JSON 之间的关系。常用的注解如下所示:

    • @JsonProperty:用来修改序列化后的 JSON 属性名,默认情况下 JSON 属性名取对象中的属性名,也可以通过 value 属性指定 JSON 属性名。如果需要的话,该注解还有一个 index 属性指定生成 JSON 属性的顺序。
    • @JsonIgnore:用于排除某个属性,这样该属性就不会被 Jackson 序列化和反序列化。
    • @JsonIgnoreProperties:这个注解定义在类上的,用来排除对象中的某些属性。比如在序列化 JSON 的时候,@JsonIgnoreProperties({"prop1", "prop2"}) 会忽略 pro1 和 pro2 两个属性。在从 JSON 反序列化为 Java 类的时候,@JsonIgnoreProperties(ignoreUnknown=true) 会忽略所有没有 Getter 和 Setter 的属性。该注解在 Java 类和 JSON 不完全匹配的时候很有用。
    • @JsonIgnoreType:也是定义在类上的,会排除所有指定类型的属性。
    • @JsonPropertyOrder:@JsonPropertyOrder 和 @JsonProperty 的 index 属性类似,用来指定属性序列化时的顺序。
    • @JsonRootName:用于指定 JSON 根属性的名称。
    • @JsonInclude:@JsonInclude(JsonInclude.Include.NON_NULL):对值为 null 的属性不进行序列化
    • @JsonFormat:添加到需要指定格式的日期属性上,指定日期属性序列化与反序列化时的格式。timezone = “GMT+8” 设置时区,表示 +8 小时,否则会少8小时。ObjectMapper 序列化 POJO 对象为 json 字符串时,Date 日期类型默认会转为 long 长整型,json 字符串反序列化为 POJO 时自动将长整型的日期转为 Date 类型。

    1.2 Jackson 的使用

    第一步:导入依赖

    jackson-databind 内部依赖了 jackson-annotations 与 jackson-core,所以 Maven 应用时,只要导入 databind 一个,则同时也导入了 annotations 与 core 依赖。

    1. <dependency>
    2. <groupId>com.fasterxml.jackson.coregroupId>
    3. <artifactId>jackson-databindartifactId>
    4. <version>2.11.0version>
    5. dependency>

    如果是 springboot 项目,它内部已经包含了 Jackson,只需要引入 web 模块即可

    二、时间相关

    1. import com.google.common.collect.Lists;
    2. import lombok.extern.slf4j.Slf4j;
    3. import org.apache.commons.lang3.time.DateFormatUtils;
    4. import org.apache.commons.lang3.time.DateUtils;
    5. import java.text.ParseException;
    6. import java.text.SimpleDateFormat;
    7. import java.time.Instant;
    8. import java.time.LocalDateTime;
    9. import java.time.LocalTime;
    10. import java.time.ZoneId;
    11. import java.time.format.DateTimeFormatter;
    12. import java.util.*;
    13. /**
    14. * 时间工具类
    15. */
    16. @Slf4j
    17. public class DateUtil {
    18. /*** 常用的时间模型常量*/
    19. public static final String PATTERN_DATE_TIME_MONTH = "yyyy-MM-dd";
    20. private static final String PATTERN_DATE_TIME = "yyyy-MM-dd HH:mm:ss";
    21. public static final String PATTERN_DATE_TIME_MILLISECOND = "yyyy-MM-dd HH:mm:ss.SSS";
    22. private static final String EXPORT_FORMAT_DATE_TIME = "yyyyMMdd-hhmmss";
    23. /*** 周末*/
    24. public static List holidays = Lists.newArrayList(6, 7);
    25. /*** 工作日*/
    26. public static List workdays = Lists.newArrayList(1, 2, 3, 4, 5);
    27. /**
    28. * 获取指定的format,每次重建避免线程安全问题 yyyy-MM-dd HH:mm:ss
    29. */
    30. public static SimpleDateFormat getYyyyMmDdHhMmSs() {
    31. return new SimpleDateFormat(PATTERN_DATE_TIME);
    32. }
    33. /**
    34. * LocalDateTime转为String,格式为:"2023-10-13 15:40:23"
    35. */
    36. public static String formatDateTime(LocalDateTime dateTime) {
    37. if (Objects.isNull(dateTime)) {
    38. return "";
    39. }
    40. DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PATTERN_DATE_TIME);
    41. return dateTime.format(formatter);
    42. }
    43. /**
    44. * LocalDateTime转为String,格式为:"2023-10-13"
    45. */
    46. public static String formatDateTimeOfMonth(LocalDateTime dateTime) {
    47. if (Objects.isNull(dateTime)) {
    48. return "";
    49. }
    50. DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PATTERN_DATE_TIME_MONTH);
    51. return dateTime.format(formatter);
    52. }
    53. /**
    54. * LocalDateTime转为Date
    55. */
    56. public static Date localDateTimeToDate(LocalDateTime localDateTime) {
    57. return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    58. }
    59. /**
    60. * LocalDateTime转为时间戳
    61. */
    62. public static String dateTimestamp(LocalDateTime date) {
    63. return DateTimeFormatter.ofPattern("yyMMddHHmmssSSS").format(date);
    64. }
    65. /**
    66. * LocalDateTime转为String,自定义时间格式
    67. *
    68. * @param dateTime LocalDateTime类型的时间
    69. * @param pattern 自定义的时间格式
    70. */
    71. public static String formatDateTime(LocalDateTime dateTime, String pattern) {
    72. if (Objects.isNull(dateTime)) {
    73. return "";
    74. }
    75. DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
    76. return dateTime.format(formatter);
    77. }
    78. /**
    79. * Date转为String,格式为:“2023-01-01”
    80. */
    81. public static String formatDateTime(Date dateTime) {
    82. if (Objects.nonNull(dateTime)) {
    83. return DateFormatUtils.format(dateTime, PATTERN_DATE_TIME_MONTH);
    84. }
    85. return "";
    86. }
    87. /**
    88. * Date转为String,格式为:“2023-01-01 12:10:50”
    89. */
    90. public static String formatDateOfDate(Date dateTime) {
    91. if (Objects.nonNull(dateTime)) {
    92. return DateFormatUtils.format(dateTime, PATTERN_DATE_TIME);
    93. }
    94. return "";
    95. }
    96. /**
    97. * Date转为String,格式为:“20230101-121050”
    98. */
    99. public static String exportFormatDateTime(Date dateTime) {
    100. if (Objects.nonNull(dateTime)) {
    101. return DateFormatUtils.format(dateTime, EXPORT_FORMAT_DATE_TIME);
    102. }
    103. return "";
    104. }
    105. /**
    106. * Date转为String,格式为:“2023.01.01”
    107. */
    108. public static String formatDate(Date dateTime) {
    109. if (Objects.nonNull(dateTime)) {
    110. return DateFormatUtils.format(dateTime, "yyyy.MM.dd");
    111. }
    112. return "";
    113. }
    114. /**
    115. * Date转为String时间,自定义时间格式
    116. *
    117. * @param dateTime Date时间
    118. * @param pattern 自定义的时间格式
    119. */
    120. public static String formatDateTime(Date dateTime, String pattern) {
    121. if (Objects.nonNull(dateTime)) {
    122. return DateFormatUtils.format(dateTime, pattern);
    123. }
    124. return "";
    125. }
    126. /**
    127. * 字符串时间转为Date,格式为:"Sun Oct 01 00:00:00 CST 2023"
    128. */
    129. public static Date strToDateTimeOfMonth(String strDate) {
    130. try {
    131. strDate = strDate.substring(0, 10);
    132. return DateUtils.parseDate(strDate, PATTERN_DATE_TIME_MONTH);
    133. } catch (ParseException e) {
    134. log.error("时间转换异常:{}", e.getMessage());
    135. throw new RuntimeException(e);
    136. }
    137. }
    138. /**
    139. * 字符串时间转为Date,格式为:"Sun Oct 01 02:56:20 CST 2023"
    140. */
    141. public static Date strToDateTime(String strDate) {
    142. if (strDate.length() != 19) {
    143. throw new RuntimeException("入参时间格式不正确");
    144. }
    145. try {
    146. return DateUtils.parseDate(strDate, PATTERN_DATE_TIME);
    147. } catch (ParseException e) {
    148. log.error("时间转换异常:{}", e.getMessage());
    149. throw new RuntimeException(e);
    150. }
    151. }
    152. /**
    153. * 将Date对象转化为指定格式dateFormat的字符串
    154. *
    155. * @return String
    156. */
    157. public static String getDate(Date date, String dateFormat) {
    158. SimpleDateFormat format = new SimpleDateFormat(dateFormat);
    159. return format.format(date);
    160. }
    161. /**
    162. * 将指定格式fromFormat的Date字符串转化为Date对象
    163. */
    164. public static Date getDate(String date) {
    165. SimpleDateFormat sdf = getYyyyMmDdHhMmSs();
    166. try {
    167. return sdf.parse(date);
    168. } catch (Exception e) {
    169. e.printStackTrace();
    170. }
    171. return null;
    172. }
    173. /**
    174. * 将指定格式fromFormat的Date字符串转化为Date对象
    175. *
    176. * @return Date
    177. */
    178. public static Date getDate(String date, String fromFormat) {
    179. try {
    180. SimpleDateFormat fromSimpleDateFormat = new SimpleDateFormat(fromFormat);
    181. return fromSimpleDateFormat.parse(date);
    182. } catch (Exception e) {
    183. e.printStackTrace();
    184. }
    185. return null;
    186. }
    187. /**
    188. * 字符串时间转为LocalDateTime,格式为:"2023-10-01T02:56:20"
    189. */
    190. public static LocalDateTime strToLocalDateTime(String strDate) {
    191. if (strDate.length() != 19) {
    192. throw new RuntimeException("入参时间格式不正确");
    193. }
    194. try {
    195. Date date = DateUtils.parseDate(strDate, "yyyy-MM-dd HH:mm:ss");
    196. return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    197. } catch (ParseException e) {
    198. log.error("时间转换异常:{}", e.getMessage());
    199. throw new RuntimeException(e);
    200. }
    201. }
    202. /**
    203. * 字符串时间转为LocalDateTime,格式为:"2023-10-01T02:56:20.001"
    204. */
    205. public static LocalDateTime strToLocalDateTimeMillisecond(String strDate) {
    206. try {
    207. if (strDate.length() != 23) {
    208. throw new RuntimeException("入参时间格式不正确");
    209. }
    210. Date date = DateUtils.parseDate(strDate, PATTERN_DATE_TIME_MILLISECOND);
    211. return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    212. } catch (ParseException e) {
    213. log.error("时间转换异常:{}", e.getMessage());
    214. throw new RuntimeException(e);
    215. }
    216. }
    217. /**
    218. * 计算两个时间差
    219. */
    220. public static String getDatePoor(Date endDate, Date nowDate) {
    221. long nd = 1000 * 24 * 60 * 60;
    222. long nh = 1000 * 60 * 60;
    223. long nm = 1000 * 60;
    224. // long ns = 1000;
    225. // 获得两个时间的毫秒时间差异
    226. long diff = Math.abs(endDate.getTime() - nowDate.getTime());
    227. // 计算差多少天
    228. long day = diff / nd;
    229. // 计算差多少小时
    230. long hour = diff % nd / nh;
    231. // 计算差多少分钟
    232. long min = diff % nd % nh / nm;
    233. // 计算差多少秒//输出结果
    234. // long sec = diff % nd % nh % nm / ns;
    235. return day + "天" + hour + "小时" + min + "分钟";
    236. }
    237. /**
    238. * 计算两个时间相差天数
    239. */
    240. public static int differentDaysByMillisecond(Date date1, Date date2) {
    241. return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    242. }
    243. /**
    244. * 计算两个时间相差小时
    245. */
    246. public static int differentHourByMillisecond(Date date1, Date date2) {
    247. return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600)));
    248. }
    249. /**
    250. * 计算两个时间相差分钟
    251. */
    252. public static int differentMinByMillisecond(Date date1, Date date2) {
    253. return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 60)));
    254. }
    255. /**
    256. * 获得某天最大时间,例如:Wed Nov 29 23:59:59 CST 2023
    257. */
    258. public static Date getEndOfDay(Date date) {
    259. LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());
    260. LocalDateTime endOfDay = localDateTime.with(LocalTime.MAX);
    261. return Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
    262. }
    263. /**
    264. * 获得某天最小时间,例如:Wed Nov 29 00:00:00 CST 2023
    265. */
    266. public static Date getStartOfDay(Date date) {
    267. LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());
    268. LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN);
    269. return Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
    270. }
    271. /**
    272. * 获取相对于date前后的某一天
    273. */
    274. public static Date anotherDay(Date date, int i) {
    275. Calendar cal = Calendar.getInstance();
    276. cal.setTime(date);
    277. cal.add(Calendar.DATE, i);
    278. return cal.getTime();
    279. }
    280. /**
    281. * 给定值向后加月份
    282. */
    283. public static Date stepMonth(Date sourceDate, int month) {
    284. Calendar c = Calendar.getInstance();
    285. c.setTime(sourceDate);
    286. c.add(Calendar.MONTH, month);
    287. return c.getTime();
    288. }
    289. /**
    290. * 给定值向后加年份
    291. */
    292. public static Date stepYear(Date sourceDate, int year) {
    293. Calendar c = Calendar.getInstance();
    294. c.setTime(sourceDate);
    295. c.add(Calendar.YEAR, year);
    296. return c.getTime();
    297. }
    298. /**
    299. * 该年最后一天的 时、分、秒以23:59:59结尾
    300. */
    301. public static Date dateTimeYearEndWidth(Date dateTime) {
    302. String dateTimeString = getDate(dateTime, PATTERN_DATE_TIME);
    303. return getDate(dateTimeString.substring(0, 4) + "-12-31 23:59:59");
    304. }
    305. /**
    306. * 获取过去N天内的日期数组(不包含今天)返回的时间类型为:yyyy-MM-dd
    307. */
    308. public static ArrayList getLastDays(int intervals) {
    309. ArrayList pastDaysList = new ArrayList<>();
    310. for (int i = intervals; i > 0; i--) {
    311. Calendar calendar = Calendar.getInstance();
    312. calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - i);
    313. Date today = calendar.getTime();
    314. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    315. pastDaysList.add(format.format(today));
    316. }
    317. return pastDaysList;
    318. }
    319. }

    三、正则校验

    1. import java.util.ArrayList;
    2. import java.util.List;
    3. import java.util.regex.Matcher;
    4. import java.util.regex.Pattern;
    5. /**
    6. * 正则相关工具类
    7. */
    8. public class ValidateUtil {
    9. /*** 手机号(简单),以1开头的11位纯数字*/
    10. public static final String REGEX_MOBILE_SIMPLE = "^[1]\\d{10}$";
    11. /**
    12. * 手机号(精确)
    13. *

      移动:134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、178、182、183、184、187、188

    14. *

      联通:130、131、132、145、155、156、175、176、185、186

    15. *

      电信:133、153、173、177、180、181、189

    16. *

      全球星:1349

    17. *

      虚拟运营商:170

    18. */
    19. public static final String REGEX_MOBILE_EXACT = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|(147))\\d{8}$";
    20. /*** 固定电话号码*/
    21. public static final String REGEX_TEL = "^0\\d{2,3}[- ]?\\d{7,8}";
    22. /*** 身份证号(15位身份证号)*/
    23. public static final String REGEX_ID_CARD15 = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$";
    24. /*** 身份证号(18位身份证号)*/
    25. public static final String REGEX_ID_CARD18 = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9Xx])$";
    26. /*** 身份证号(15和18位)*/
    27. public static final String REGEX_ID_CARD15AND18 = "(^\\d{8}(0\\d|10|11|12)([0-2]\\d|30|31)\\d{3}$)|(^\\d{6}(18|19|20)\\d{2}(0\\d|10|11|12)([0-2]\\d|30|31)\\d{3}(\\d|X|x)$)";
    28. /*** 邮箱*/
    29. public static final String REGEX_EMAIL = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
    30. /*** 网址URL*/
    31. public static final String REGEX_URL = "[a-zA-z]+://[^\\s]*";
    32. /*** 汉字*/
    33. public static final String REGEX_ZH = "^[\\u4e00-\\u9fa5]+$";
    34. /*** 用户名(取值范围为a-z,A-Z,0-9,"_",汉字,不能以"_"结尾,用户名必须是6-20位)*/
    35. public static final String REGEX_USERNAME = "^[\\w\\u4e00-\\u9fa5]{6,20}(?;
    36. /*** yyyy-MM-dd格式的日期校验,已考虑平闰年*/
    37. public static final String REGEX_DATE = "^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$";
    38. /*** IP地址*/
    39. public static final String REGEX_IP = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)";
    40. /*** 双字节字符(包括汉字在内)*/
    41. public static final String REGEX_DOUBLE_BYTE_CHAR = "[^\\x00-\\xff]";
    42. /*** 空白行*/
    43. public static final String REGEX_BLANK_LINE = "\\n\\s*\\r";
    44. /*** QQ号*/
    45. public static final String REGEX_TENCENT_NUM = "[1-9][0-9]{4,}";
    46. /*** 中国邮政编码*/
    47. public static final String REGEX_ZIP_CODE = "[1-9]\\d{5}(?!\\d)";
    48. /*** 正整数*/
    49. public static final String REGEX_POSITIVE_INTEGER = "^[1-9]\\d*$";
    50. /*** 负整数*/
    51. public static final String REGEX_NEGATIVE_INTEGER = "^-[1-9]\\d*$";
    52. /*** 整数*/
    53. public static final String REGEX_INTEGER = "^-?[1-9]\\d*$";
    54. /*** 非负整数(正整数 + 0)*/
    55. public static final String REGEX_NOT_NEGATIVE_INTEGER = "^[1-9]\\d*|0$";
    56. /*** 非正整数(负整数 + 0)*/
    57. public static final String REGEX_NOT_POSITIVE_INTEGER = "^-[1-9]\\d*|0$";
    58. /*** 正浮点数*/
    59. public static final String REGEX_POSITIVE_FLOAT = "^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*$";
    60. /*** 负浮点数*/
    61. public static final String REGEX_NEGATIVE_FLOAT = "^-[1-9]\\d*\\.\\d*|-0\\.\\d*[1-9]\\d*$";
    62. /**
    63. * 验证手机号(简单)
    64. *
    65. * @param input 待验证文本
    66. * @return true: 匹配
      false: 不匹配
    67. */
    68. public static boolean isMobileSimple(CharSequence input) {
    69. return isMatch(REGEX_MOBILE_SIMPLE, input);
    70. }
    71. /**
    72. * 验证手机号(精确)
    73. *
    74. * @param input 待验证文本
    75. * @return true: 匹配
      false: 不匹配
    76. */
    77. public static boolean isMobileExact(CharSequence input) {
    78. return isMatch(REGEX_MOBILE_EXACT, input);
    79. }
    80. /**
    81. * 验证固定电话号码
    82. *
    83. * @param input 待验证文本
    84. * @return true: 匹配
      false: 不匹配
    85. */
    86. public static boolean isTel(CharSequence input) {
    87. return isMatch(REGEX_TEL, input);
    88. }
    89. /**
    90. * 验证身份证号码(15位)
    91. *
    92. * @param input 待验证文本
    93. * @return true: 匹配
      false: 不匹配
    94. */
    95. public static boolean isIdCard15(CharSequence input) {
    96. return isMatch(REGEX_ID_CARD15, input);
    97. }
    98. /**
    99. * 验证身份证号码(18位)
    100. *
    101. * @param input 待验证文本
    102. * @return true: 匹配
      false: 不匹配
    103. */
    104. public static boolean isIdCard18(CharSequence input) {
    105. return isMatch(REGEX_ID_CARD18, input);
    106. }
    107. /**
    108. * 验证身份证号码(15/18位)
    109. *
    110. * @param input 待验证文本
    111. * @return true: 匹配
      false: 不匹配
    112. */
    113. public static boolean isIdCard15and18(CharSequence input) {
    114. return isMatch(REGEX_ID_CARD15AND18, input);
    115. }
    116. /**
    117. * 验证邮箱
    118. *
    119. * @param input 待验证文本
    120. * @return true: 匹配
      false: 不匹配
    121. */
    122. public static boolean isEmail(CharSequence input) {
    123. return isMatch(REGEX_EMAIL, input);
    124. }
    125. /**
    126. * 验证网址URL
    127. *
    128. * @param input 待验证文本
    129. * @return true: 匹配
      false: 不匹配
    130. */
    131. public static boolean isUrl(CharSequence input) {
    132. return isMatch(REGEX_URL, input);
    133. }
    134. /**
    135. * 验证汉字
    136. *
    137. * @param input 待验证文本
    138. * @return true: 匹配
      false: 不匹配
    139. */
    140. public static boolean isZh(CharSequence input) {
    141. return isMatch(REGEX_ZH, input);
    142. }
    143. /**
    144. * 验证用户名(取值范围为a-z,A-Z,0-9,"_",汉字,不能以"_"结尾,用户名必须是6-20位)
    145. *
    146. * @param input 待验证文本
    147. * @return true: 匹配
      false: 不匹配
    148. */
    149. public static boolean isUsername(CharSequence input) {
    150. return isMatch(REGEX_USERNAME, input);
    151. }
    152. /**
    153. * 验证yyyy-MM-dd格式的日期校验,已考虑平闰年
    154. *
    155. * @param input 待验证文本
    156. * @return true: 匹配
      false: 不匹配
    157. */
    158. public static boolean isDate(CharSequence input) {
    159. return isMatch(REGEX_DATE, input);
    160. }
    161. /**
    162. * 验证IP地址
    163. *
    164. * @param input 待验证文本
    165. * @return true: 匹配
      false: 不匹配
    166. */
    167. public static boolean isIp(CharSequence input) {
    168. return isMatch(REGEX_IP, input);
    169. }
    170. /**
    171. * 判断是否匹配正则
    172. *
    173. * @param regex 正则表达式
    174. * @param input 要匹配的字符串
    175. * @return true: 匹配
      false: 不匹配
    176. */
    177. public static boolean isMatch(String regex, CharSequence input) {
    178. return input != null && input.length() > 0 && Pattern.matches(regex, input);
    179. }
    180. /**
    181. * 获取正则匹配的部分
    182. *
    183. * @param regex 正则表达式
    184. * @param input 要匹配的字符串
    185. * @return 正则匹配的部分
    186. */
    187. public static List getMatches(String regex, CharSequence input) {
    188. if (input == null) {
    189. return null;
    190. }
    191. List matches = new ArrayList<>();
    192. Pattern pattern = Pattern.compile(regex);
    193. Matcher matcher = pattern.matcher(input);
    194. while (matcher.find()) {
    195. matches.add(matcher.group());
    196. }
    197. return matches;
    198. }
    199. /**
    200. * 获取正则匹配分组
    201. *
    202. * @param input 要分组的字符串
    203. * @param regex 正则表达式
    204. * @return 正则匹配分组
    205. */
    206. public static String[] getSplits(String input, String regex) {
    207. if (input == null) {
    208. return null;
    209. }
    210. return input.split(regex);
    211. }
    212. /**
    213. * 替换正则匹配的第一部分
    214. *
    215. * @param input 要替换的字符串
    216. * @param regex 正则表达式
    217. * @param replacement 代替者
    218. * @return 替换正则匹配的第一部分
    219. */
    220. public static String getReplaceFirst(String input, String regex, String replacement) {
    221. if (input == null) {
    222. return null;
    223. }
    224. return Pattern.compile(regex).matcher(input).replaceFirst(replacement);
    225. }
    226. /**
    227. * 替换所有正则匹配的部分
    228. *
    229. * @param input 要替换的字符串
    230. * @param regex 正则表达式
    231. * @param replacement 代替者
    232. * @return 替换所有正则匹配的部分
    233. */
    234. public static String getReplaceAll(String input, String regex, String replacement) {
    235. if (input == null) {
    236. return null;
    237. }
    238. return Pattern.compile(regex).matcher(input).replaceAll(replacement);
    239. }
    240. }

    四、JWT

    第一步:导入坐标

    1. <dependency>
    2. <groupId>io.jsonwebtokengroupId>
    3. <artifactId>jjwtartifactId>
    4. <version>0.9.1version>
    5. dependency>

    第二步:在项目导入jwt工具类

    1. import com.auth0.jwt.JWT;
    2. import com.auth0.jwt.algorithms.Algorithm;
    3. import com.auth0.jwt.interfaces.Claim;
    4. import com.auth0.jwt.interfaces.DecodedJWT;
    5. import com.auth0.jwt.interfaces.JWTVerifier;
    6. import lombok.extern.slf4j.Slf4j;
    7. import org.apache.commons.lang3.StringUtils;
    8. import org.springframework.beans.factory.annotation.Value;
    9. import org.springframework.stereotype.Component;
    10. import java.util.Date;
    11. import java.util.Map;
    12. import java.util.Optional;
    13. /**
    14. * jwt的token生成与解析
    15. */
    16. @Slf4j
    17. @Component
    18. public class JwtUtils {
    19. /**
    20. * token秘钥,请勿泄露,请勿随便修改
    21. */
    22. @Value("${mallchat.jwt.secret}")
    23. private String secret;
    24. private static final String UID_CLAIM = "uid";
    25. private static final String CREATE_TIME = "createTime";
    26. /**
    27. * JWT生成Token
    28. * JWT构成: header, payload, signature
    29. */
    30. public String createToken(Long uid) {
    31. String token = JWT.create()
    32. .withClaim(UID_CLAIM, uid) //只存一个uid信息,其他的自己去redis查
    33. .withClaim(CREATE_TIME, new Date())
    34. .sign(Algorithm.HMAC256(secret)); //signature
    35. return token;
    36. }
    37. /**
    38. * 解密Token
    39. */
    40. public Map verifyToken(String token) {
    41. if (StringUtils.isEmpty(token)) {
    42. return null;
    43. }
    44. try {
    45. JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
    46. DecodedJWT jwt = verifier.verify(token);
    47. return jwt.getClaims();
    48. } catch (Exception e) {
    49. log.error("decode error,token:{}", token, e);
    50. }
    51. return null;
    52. }
    53. /**
    54. * 根据Token获取uid
    55. */
    56. public Long getUidOrNull(String token) {
    57. return Optional.ofNullable(verifyToken(token))
    58. .map(map -> map.get(UID_CLAIM))
    59. .map(Claim::asLong)
    60. .orElse(null);
    61. }
    62. }

  • 相关阅读:
    Python3 OS 文件/目录方法
    css 10-13
    (附源码)计算机毕业设计SSM基于框架的旅游管理系统
    24、DAPlink仿真器-STM32F103C8T6
    基于人工大猩猩部队算法优化概率神经网络PNN的分类预测 - 附代码
    Go Web---上
    【JAVA并发】二、JAVA是如何解决并发问题的
    java验证码的实现
    使用go开发的小tips
    ts 分发
  • 原文地址:https://blog.csdn.net/m0_59749089/article/details/137976898