验证码

r囧r小猫 2022-07-16 08:28 301阅读 0赞

验证码的验证是我们登陆网页时经常进行的操作,我也做了一个简单的验证码,包括颜色以及噪线等等

  1. @RequestMapping(value = "/Frame/VerifyCode", method = RequestMethod.GET)
  2. public @ResponseBody ModelAndView VerifyCode(HttpServletRequest request, HttpServletResponse response, HttpSession httpSession) {
  3. int codeW = 80;
  4. int codeH = 22;
  5. int fontSize = 16;
  6. // 颜色列表,用于验证码、噪线、噪点
  7. Color[] color = { Color.BLACK, Color.RED, Color.BLUE, Color.GREEN, Color.ORANGE, Color.GRAY, Color.YELLOW };
  8. // 字体列表,用于验证码
  9. String[] font = { "Verdana" };
  10. // 验证码的字符集,去掉了一些容易混淆的字符
  11. String[] character = { "2", "3", "4", "5", "6", "8", "9", "a", "b", "d", "e", "f", "h", "k", "m", "n", "r", "x",
  12. "y", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "R", "S", "T", "W", "X",
  13. "Y" };
  14. Random rnd = new Random();
  15. String chkCode[] = new String[4];
  16. // 生成验证码字符串
  17. for (int i = 0; i < 4; i++) {
  18. chkCode[i] = character[rnd.nextInt(character.length)];
  19. }
  20. // 创建画布
  21. BufferedImage image = new BufferedImage(codeW, codeH, BufferedImage.TYPE_INT_RGB);
  22. Graphics g = image.getGraphics();
  23. Color clr = color[rnd.nextInt(color.length)];
  24. // 设置背景色
  25. g.setColor(Color.DARK_GRAY);
  26. g.setFont(new Font("Verdana",0,26));
  27. g.fillRect(0, 0, codeW, codeH);
  28. // g.setColor(clr);
  29. // 画噪线
  30. for (int i = 0; i < 1; i++) {
  31. int x1 = rnd.nextInt(codeW);
  32. int y1 = rnd.nextInt(codeH);
  33. int x2 = rnd.nextInt(codeW);
  34. int y2 = rnd.nextInt(codeH);
  35. clr = color[rnd.nextInt(color.length)];
  36. g.setColor(clr);
  37. g.drawLine(x1, y1, x2, y2);
  38. }
  39. String codeCheck = "";
  40. // 画验证码字符串
  41. for (int i = 0; i < chkCode.length; i++) {
  42. clr = color[rnd.nextInt(color.length)];
  43. g.setColor(clr);
  44. g.drawString(chkCode[i], 20*i, 20);
  45. codeCheck += chkCode[i];
  46. }
  47. OutputStream out = null;
  48. try {
  49. out = response.getOutputStream();
  50. ImageIO.write(image, "JPEG", out);
  51. out.flush();
  52. out.close();
  53. System.out.println("生成的验证码:code="+chkCode);
  54. httpSession.setAttribute("SESSION_CHECKCODE", codeCheck);
  55. }
  56. catch(Exception e)
  57. {
  58. e.printStackTrace();
  59. }
  60. return null;
  61. }

发表评论

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

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

相关阅读

    相关 验证

    验证码的验证是我们登陆网页时经常进行的操作,我也做了一个简单的验证码,包括颜色以及噪线等等 @RequestMapping(value = "/Frame/Verif

    相关 验证

    1、需求      在访问登录页面时,需要生产验证码。从而防止用户使用程序恶意登录。 2、代码实现      步骤1:修改登录页面,确定验证码图片显示的位置 !

    相关 验证

    验证码 google验证码kaptcha Java验证码 patchca 验证码工具类 google验证码kaptcha [https://bl

    相关 验证---短信验证

    最近自学了短信的验证码实现。以下是自己用的一种方法实现的完整的过程。 短信验证登陆(前端+后台) 1、前端填写手机号以及点击触发,以电话号码为参数调用发送验证登录短信方法并