java验证码工具类

超、凢脫俗 2023-02-25 07:02 87阅读 0赞
  1. package com.jdkj.charge.common.utils;
  2. import java.util.Random;
  3. public class ValidCodeUtils {
  4. private static char[] numbers = "0123456789".toCharArray();
  5. private static char[] words = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ".toCharArray();
  6. private static final int MIN_LEN = 4;
  7. private static final int MAX_LEN = 8;
  8. /**
  9. * @param len
  10. * @return
  11. * @author: ChenYan
  12. * @date: 2019年4月24日
  13. * @description: 返回数字验证码
  14. */
  15. public static String generateNumber(int len) {
  16. len = limitLen(len);
  17. Random random = new Random();
  18. char[] cs = new char[len];
  19. for (int i = 0; i < cs.length; i++) {
  20. cs[i] = numbers[random.nextInt(numbers.length)];
  21. }
  22. return new String(cs);
  23. }
  24. /**
  25. * @param len
  26. * @return
  27. * @author: ChenYan
  28. * @date: 2019年4月24日
  29. * @description: 返回字符数字混合型验证码
  30. */
  31. public static String generateCode(int len) {
  32. len = limitLen(len);
  33. Random random = new Random();
  34. char[] cs = new char[len];
  35. for (int i = 0; i < cs.length; i++) {
  36. cs[i] = words[random.nextInt(words.length)];
  37. }
  38. return new String(cs);
  39. }
  40. /**
  41. * @param len
  42. * @return
  43. * @author: ChenYan
  44. * @date: 2019年4月24日
  45. * @description: 限制验证码长度
  46. */
  47. private static int limitLen(int len) {
  48. if (len < MIN_LEN) {
  49. return MIN_LEN;
  50. } else if (len > MAX_LEN) {
  51. return MAX_LEN;
  52. } else {
  53. return len;
  54. }
  55. }
  56. public static void main(String[] args) {
  57. String code = ValidCodeUtils.generateCode(6);
  58. System.out.println("code====" + code);
  59. String number = ValidCodeUtils.generateNumber(6);
  60. System.out.println("number====" + number);
  61. }
  62. }

发表评论

表情:
评论列表 (有 0 条评论,87人围观)

还没有评论,来说两句吧...

相关阅读