java web 图片验证码

喜欢ヅ旅行 2022-03-10 04:48 317阅读 0赞

1.验证码生成工具类

  1. package com.dzqc.dz.common.controller;
  2. import javax.imageio.ImageIO;
  3. import java.awt.*;
  4. import java.awt.image.BufferedImage;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.OutputStream;
  8. import java.util.Date;
  9. import java.util.Random;
  10. /**
  11. * 验证码生成工具类
  12. */
  13. public class ValidateCode {
  14. // 图片的宽度。
  15. private int width = 160;
  16. // 图片的高度。
  17. private int height = 40;
  18. // 验证码字符个数
  19. private int codeCount = 5;
  20. // 验证码干扰线数
  21. private int lineCount = 150;
  22. // 验证码
  23. private String code = null;
  24. // 验证码图片Buffer
  25. private BufferedImage buffImg = null;
  26. // 验证码范围,去掉0(数字)和O(拼音)容易混淆的(小写的1和L也可以去掉,大写不用了)
  27. private char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
  28. 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  29. 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
  30. /**
  31. * 默认构造函数,设置默认参数
  32. */
  33. public ValidateCode() {
  34. this.createCode();
  35. }
  36. /**
  37. * @param width 图片宽
  38. * @param height 图片高
  39. */
  40. public ValidateCode(int width, int height) {
  41. this.width = width;
  42. this.height = height;
  43. this.createCode();
  44. }
  45. /**
  46. * @param width 图片宽
  47. * @param height 图片高
  48. * @param codeCount 字符个数
  49. * @param lineCount 干扰线条数
  50. */
  51. public ValidateCode(int width, int height, int codeCount, int lineCount) {
  52. this.width = width;
  53. this.height = height;
  54. this.codeCount = codeCount;
  55. this.lineCount = lineCount;
  56. this.createCode();
  57. }
  58. public void createCode() {
  59. int x = 0, fontHeight = 0, codeY = 0;
  60. int red = 0, green = 0, blue = 0;
  61. x = width / (codeCount + 2);//每个字符的宽度(左右各空出一个字符)
  62. fontHeight = height - 2;//字体的高度
  63. codeY = height - 4;
  64. // 图像buffer
  65. buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  66. Graphics2D g = buffImg.createGraphics();
  67. /*// 将图像背景填充为白色
  68. g.setColor(Color.WHITE);
  69. g.fillRect(0, 0, width, height);*/
  70. // 增加下面代码使得背景透明
  71. buffImg = g.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
  72. g.dispose();
  73. g = buffImg.createGraphics();
  74. // 背景透明代码结束
  75. // 画图BasicStroke是JDK中提供的一个基本的画笔类,我们对他设置画笔的粗细,就可以在drawPanel上任意画出自己想要的图形了。
  76. g.setColor(new Color(255, 0, 0));
  77. g.setStroke(new BasicStroke(1f));
  78. g.fillRect(128, 128, width, height);
  79. // 生成随机数
  80. Random random = new Random();
  81. //设置字体类型、字体大小、字体样式 
  82. Font font = new Font("微软雅黑",Font.PLAIN, fontHeight);
  83. g.setFont(font);
  84. for (int i = 0; i < lineCount; i++) {
  85. // 设置随机开始和结束坐标
  86. int xs = random.nextInt(width);//x坐标开始
  87. int ys = random.nextInt(height);//y坐标开始
  88. int xe = xs + random.nextInt(width / 8);//x坐标结束
  89. int ye = ys + random.nextInt(height / 8);//y坐标结束
  90. // 产生随机的颜色值,让输出的每个干扰线的颜色值都将不同。
  91. red = random.nextInt(255);
  92. green = random.nextInt(255);
  93. blue = random.nextInt(255);
  94. g.setColor(new Color(red, green, blue));
  95. g.drawLine(xs, ys, xe, ye);
  96. }
  97. // randomCode记录随机产生的验证码
  98. StringBuffer randomCode = new StringBuffer();
  99. // 随机产生codeCount个字符的验证码。
  100. for (int i = 0; i < codeCount; i++) {
  101. String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
  102. // 产生随机的颜色值,让输出的每个字符的颜色值都将不同。
  103. red = random.nextInt(255);
  104. green = random.nextInt(255);
  105. blue = random.nextInt(255);
  106. //指定某种颜色
  107. //g.setColor(new Color(252, 145, 83));
  108. g.setColor(new Color(red, green, blue));
  109. g.drawString(strRand, (i + 1) * x, codeY);
  110. // 将产生的四个随机数组合在一起。
  111. randomCode.append(strRand);
  112. }
  113. // 将四位数字的验证码保存到Session中。
  114. code = randomCode.toString();
  115. }
  116. public void write(String path) throws IOException {
  117. OutputStream sos = new FileOutputStream(path);
  118. this.write(sos);
  119. }
  120. public void write(OutputStream sos) throws IOException {
  121. ImageIO.write(buffImg, "png", sos);
  122. sos.close();
  123. }
  124. public BufferedImage getBuffImg() {
  125. return buffImg;
  126. }
  127. public String getCode() {
  128. return code;
  129. }
  130. /**
  131. * 测试函数,默认生成到d盘
  132. * @param args
  133. */
  134. public static void main(String[] args) {
  135. ValidateCode vCode = new ValidateCode(160,40,5,150);
  136. try {
  137. String path="D:/"+new Date().getTime()+".png";
  138. System.out.println(vCode.getCode()+" >"+path);
  139. vCode.write(path);
  140. } catch (IOException e) {
  141. e.printStackTrace();
  142. }
  143. }
  144. }

2.控制层代码:

  1. package com.dzqc.dz.common.controller;
  2. import java.io.IOException;
  3. import javax.imageio.ImageIO;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6. import javax.servlet.http.HttpSession;
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.ResponseBody;
  10. import com.dzqc.dz.common.util.MyAjaxResult;
  11. @Controller
  12. @RequestMapping("/yzm")
  13. public class TestControllers {
  14. /**
  15. * 跳转页面
  16. * @param session
  17. * @param id
  18. * @return
  19. */
  20. @RequestMapping("/yzm")
  21. public String login() {
  22. return "yzm";
  23. }
  24. /**
  25. * 获取验证码图片
  26. * @param request
  27. * @param response
  28. * @throws IOException
  29. */
  30. @RequestMapping("/user/check")
  31. public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
  32. // 通知浏览器不要缓存
  33. response.setHeader("Expires", "-1");
  34. response.setHeader("Cache-Control", "no-cache");
  35. response.setHeader("Pragma", "-1");
  36. ValidateCode vCode = new ValidateCode(160,40,5,150);
  37. // 将验证码输入到session中,用来验证
  38. String code=vCode.getCode();
  39. request.getSession().setAttribute("code", code);
  40. // 输出到web页面
  41. ImageIO.write(vCode.getBuffImg(), "jpg", response.getOutputStream());
  42. }
  43. @RequestMapping("/submit")
  44. @ResponseBody
  45. public MyAjaxResult submit(HttpSession session,String username,String password,String judge) {
  46. if(username==null||"".equals(username)) {
  47. return MyAjaxResult.fail_300("请输入用户名");
  48. }
  49. if(password==null||"".equals(password)) {
  50. return MyAjaxResult.fail_300("请输入密码");
  51. }
  52. if(judge==null||"".equals(judge)) {
  53. return MyAjaxResult.success("请输入验证码");
  54. }
  55. Object code=session.getAttribute("code");
  56. if(code==null) {
  57. return MyAjaxResult.fail_300("验证码错误,请刷新验证码");
  58. }else {
  59. if(!judge.equals(code.toString())) {
  60. session.removeAttribute("code");
  61. return MyAjaxResult.fail_500("验证码错误");
  62. }
  63. }
  64. session.removeAttribute("code");
  65. return MyAjaxResult.success("登陆成功");
  66. }
  67. }

3.jsp页面

  1. <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <title>login test</title>
  7. <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
  8. </head>
  9. <body>
  10. 用户名<input type="text" value="" name="username" id="username"><br>
  11. 密码<input type="password" value="" name="password" id="password"><br><br>
  12. <img alt="验证码" src="${path}/test/user/check" id="img"><br><br>
  13. 验证码<input type="text" value="" name="judge" id="judge"><br>
  14. <input type="button" value="提交" id="sub"><br>
  15. <script type="text/javascript">
  16. $(function(){
  17. $("#img").click(function(){
  18. var url = "${path}/test/user/check?number="+Math.random();
  19. $("#img").attr("src",url);
  20. })
  21. $("#sub").click(function(){
  22. $.ajax({
  23. url:'${path}/test/submit',
  24. dataType:'json',
  25. type:'post',
  26. data:{
  27. username:$("#username").val(),
  28. password:$("#password").val(),
  29. judge:$("#judge").val()
  30. },
  31. success:function(res){
  32. alert(res.msg)
  33. if(res.code==500){
  34. var url = "${path}/test/user/check?number="+Math.random();
  35. $("#img").attr("src",url);
  36. }
  37. },
  38. error:function(res){
  39. alert("网络错误");
  40. }
  41. })
  42. })
  43. })
  44. </script>
  45. </body>
  46. </html>

4.成功截图

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JhaWR1XzQxNjYwMTgy_size_16_color_FFFFFF_t_70

发表评论

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

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

相关阅读

    相关 Java生成图片验证

    功能介绍:自定义图片尺寸和字符长度,随机背景颜色和字符颜色,随机字符偏移角度,字符平滑边缘,干扰线,噪点,背景扭曲。 VerifyCodeUtils类,生成图片流,然后不同框