java生成随机图片验证码和验证

柔情只为你懂 2022-04-24 08:02 500阅读 0赞

先来看一下效果:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwMjA1MTE2_size_16_color_FFFFFF_t_70

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwMjA1MTE2_size_16_color_FFFFFF_t_70 1

下面来看一下代码吧!

页面部分:

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html>
  4. <html>
  5. <head>
  6. <meta charset="UTF-8">
  7. <title>学生信息管理——登录</title>
  8. <script type="text/javascript" src="static/js/jquery-1.12.4.min.js"></script>
  9. <style type="text/css">
  10. body{
  11. background: url(static/img/login.png) no-repeat;
  12. background-size: cover;
  13. }
  14. #home{
  15. width: 20%;
  16. height: 30%;
  17. margin-left: 63%;
  18. margin-top: 17%;
  19. color: #479b9b;
  20. }
  21. .inp{
  22. width: 98%;
  23. line-height: 40px;
  24. margin: 10px 0;
  25. font-size: 20px;
  26. border: none;
  27. background: #293f54;
  28. border: 2px solid #13c9a3;
  29. border-radius: 30px;
  30. }
  31. #username, #passwrod{
  32. text-indent: 1.5em;
  33. }
  34. #username{
  35. background: url(static/img/username.png) no-repeat left;
  36. }
  37. #passwrod{
  38. background: url(static/img/password.png) no-repeat left;
  39. }
  40. #btn{
  41. background: #22c1a1;
  42. }
  43. #yzm{
  44. width: 45%;
  45. text-indent: 1em;
  46. }
  47. #btn:hover{
  48. cursor: pointer;
  49. background: #33FF99;
  50. color: white;
  51. }
  52. #img{
  53. float: right;
  54. margin: 10px;
  55. }
  56. #img:hover {
  57. cursor: pointer;
  58. }
  59. </style>
  60. </head>
  61. <body>
  62. <div id="home">
  63. <form id="myForm" action="login" method="post">
  64. <input type="text" value="aaa" class="inp" name = "username" id="username" />
  65. <input type="password" value="1234" class="inp" name = "password" id="passwrod" />
  66. <input type="text" class="inp" id="yzm" placeholder="验证码" />
  67. <img id="img" src="getCode" onclick="changeImg()">
  68. <div style="margin: 10px;">
  69. <span><input type="checkbox" id="aaa"><label for="aaa">记住我</label></span>
  70. <span style="float: right;">注册</span>
  71. </div>
  72. <button type="button" class="inp" id="btn">立即登录</button>
  73. </form>
  74. </div>
  75. <script type="text/javascript">
  76. //点击更换验证码
  77. function changeImg() {
  78. var imgSrc = $("#img");
  79. var src = imgSrc.attr("src");
  80. imgSrc.attr("src", chgUrl(src));
  81. }
  82. // 时间戳
  83. // 为了使每次生成图片不一致,即不让浏览器读缓存,所以需要加上时间戳
  84. function chgUrl(url) {
  85. var timestamp = (new Date()).valueOf();
  86. url = url.substring(0, 20);
  87. if ((url.indexOf("&") >= 0)) {
  88. url = url + "×tamp=" + timestamp;
  89. } else {
  90. url = url + "?timestamp=" + timestamp;
  91. }
  92. return url;
  93. }
  94. //登录
  95. $("#btn").click(function(){
  96. var yzm = $("#yzm").val();
  97. var username = $("#username").val();
  98. var passwrod = $("#passwrod").val();
  99. $.post("yz", {yzm: yzm}, function(data){
  100. if(data.success){
  101. $("#myForm").submit();
  102. }else{
  103. alert("验证码输入错误!")
  104. }
  105. })
  106. })
  107. //监听回车事件
  108. $('#myForm').bind('keyup', function(event) {
  109. if (event.keyCode == "13") {
  110. $('#btn').click();
  111. }
  112. });
  113. </script>
  114. </body>
  115. </html>

生成验证码和验证码图片的工具类CodeUtil.java

  1. import java.awt.Color;
  2. import java.awt.Font;
  3. import java.awt.Graphics;
  4. import java.awt.image.BufferedImage;
  5. import java.awt.image.RenderedImage;
  6. import java.io.FileOutputStream;
  7. import java.io.OutputStream;
  8. import java.util.HashMap;
  9. import java.util.Map;
  10. import java.util.Random;
  11. import javax.imageio.ImageIO;
  12. public class CodeUtil {
  13. private static int width = 120;// 定义图片的width
  14. private static int height = 45;// 定义图片的height
  15. private static int codeCount = 4;// 定义图片上显示验证码的个数
  16. private static int xx = 22;
  17. private static int fontHeight = 35;
  18. private static int codeY =35;
  19. private static char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
  20. 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
  21. 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
  22. 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  23. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
  24. /**
  25. * 生成一个map集合
  26. * code为生成的验证码
  27. * codePic为生成的验证码BufferedImage对象
  28. * @return
  29. */
  30. public static Map<String,Object> generateCodeAndPic() {
  31. // 定义图像buffer
  32. BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  33. Graphics gd = buffImg.getGraphics();
  34. // 创建一个随机数生成器类
  35. Random random = new Random();
  36. // 将图像填充为白色
  37. gd.setColor(Color.WHITE);
  38. gd.fillRect(0, 0, width, height);
  39. // 创建字体,字体的大小应该根据图片的高度来定。
  40. Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
  41. // 设置字体。
  42. gd.setFont(font);
  43. // 画边框。
  44. gd.setColor(Color.BLACK);
  45. gd.drawRect(0, 0, width - 1, height - 1);
  46. // 随机产生50条干扰线,使图象中的认证码不易被其它程序探测到。
  47. gd.setColor(Color.BLACK);
  48. for (int i = 0; i < 50; i++) {
  49. int x = random.nextInt(width);
  50. int y = random.nextInt(height);
  51. int xl = random.nextInt(12);
  52. int yl = random.nextInt(12);
  53. gd.drawLine(x, y, x + xl, y + yl);
  54. }
  55. // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
  56. StringBuffer randomCode = new StringBuffer();
  57. int red = 0, green = 0, blue = 0;
  58. // 随机产生codeCount数字的验证码。
  59. for (int i = 0; i < codeCount; i++) {
  60. // 得到随机产生的验证码数字。
  61. String code = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
  62. // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。
  63. red = random.nextInt(255);
  64. green = random.nextInt(255);
  65. blue = random.nextInt(255);
  66. // 用随机产生的颜色将验证码绘制到图像中。
  67. gd.setColor(new Color(red, green, blue));
  68. gd.drawString(code, (i + 1) * xx, codeY);
  69. // 将产生的四个随机数组合在一起。
  70. randomCode.append(code);
  71. }
  72. Map<String,Object> map =new HashMap<String,Object>();
  73. //存放验证码
  74. map.put("code", randomCode);
  75. //存放生成的验证码BufferedImage对象
  76. map.put("codePic", buffImg);
  77. return map;
  78. }
  79. //测试
  80. public static void main(String[] args) throws Exception {
  81. //创建文件输出流对象
  82. OutputStream out = new FileOutputStream("D://img/"+System.currentTimeMillis()+".jpg");
  83. Map<String,Object> map = CodeUtil.generateCodeAndPic();
  84. ImageIO.write((RenderedImage) map.get("codePic"), "jpeg", out);
  85. System.out.println("验证码的值为:"+map.get("code"));
  86. }
  87. }

后台生成验证和效验代码

  1. /**
  2. * 生成验证码
  3. * @param req
  4. * @param resp
  5. */
  6. @RequestMapping(value="/getCode")
  7. @ResponseBody
  8. public void getCode(HttpServletRequest req, HttpServletResponse resp) {
  9. // 调用工具类生成的验证码和验证码图片
  10. Map<String, Object> codeMap = CodeUtil.generateCodeAndPic();
  11. // 将四位数字的验证码保存到Session中。
  12. HttpSession session = req.getSession();
  13. session.setAttribute("code", codeMap.get("code").toString());
  14. // 禁止图像缓存。
  15. resp.setHeader("Pragma", "no-cache");
  16. resp.setHeader("Cache-Control", "no-cache");
  17. resp.setDateHeader("Expires", -1);
  18. resp.setContentType("image/jpeg");
  19. // 将图像输出到Servlet输出流中。
  20. ServletOutputStream sos;
  21. try {
  22. sos = resp.getOutputStream();
  23. ImageIO.write((RenderedImage) codeMap.get("codePic"), "jpeg", sos);
  24. sos.close();
  25. } catch (IOException e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. /**
  30. * 验证验证输入是否正确
  31. * @param yzm
  32. * @param request
  33. * @return
  34. */
  35. @RequestMapping(value="/yz")
  36. @ResponseBody
  37. public Object yz(String yzm, HttpServletRequest request) {
  38. //字符串全部转为小写
  39. yzm = yzm.toLowerCase();
  40. String yzm1 = request.getSession().getAttribute("code").toString().toLowerCase();
  41. if(yzm.equals(yzm1)) {
  42. return new AjaxResult("ok");
  43. }else {
  44. return new AjaxResult(false, "no");
  45. }
  46. }

发表评论

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

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

相关阅读