IGeekShop案例9 -实现验证码功能

ゝ一纸荒年。 2024-04-17 14:10 149阅读 0赞

IGeekShop案例9 -实现验证码功能

1 改写jsp代码

在这里插入图片描述

2 编写自动生成验证码的servlet

直接使用模板
动态生成验证码Servlet代码模板

  1. package checking;
  2. import java.awt.Color;
  3. import java.awt.Font;
  4. import java.awt.Graphics;
  5. import java.awt.Graphics2D;
  6. import java.awt.image.BufferedImage;
  7. import java.io.BufferedReader;
  8. import java.io.FileReader;
  9. import java.io.IOException;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. import java.util.Random;
  13. import javax.imageio.ImageIO;
  14. import javax.servlet.ServletException;
  15. import javax.servlet.http.HttpServlet;
  16. import javax.servlet.http.HttpServletRequest;
  17. import javax.servlet.http.HttpServletResponse;
  18. /**
  19. * 验证码生成程序
  20. */
  21. public class CheckImgServlet extends HttpServlet {
  22. // 集合中保存所有成语
  23. private List<String> words = new ArrayList<String>();
  24. @Override
  25. public void init() throws ServletException {
  26. // 初始化阶段,读取new_words.txt
  27. // web工程中读取文件,必须使用绝对磁盘路径
  28. String path = getServletContext().getRealPath("/WEB-INF/new_words.txt");
  29. try {
  30. BufferedReader reader = new BufferedReader(new FileReader(path));
  31. String line;
  32. while ((line = reader.readLine()) != null) {
  33. words.add(line);
  34. }
  35. reader.close();
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. public void doGet(HttpServletRequest request, HttpServletResponse response)
  41. throws ServletException, IOException {
  42. // 禁止缓存
  43. // response.setHeader("Cache-Control", "no-cache");
  44. // response.setHeader("Pragma", "no-cache");
  45. // response.setDateHeader("Expires", -1);
  46. int width = 120;
  47. int height = 30;
  48. // 步骤一 绘制一张内存中图片
  49. BufferedImage bufferedImage = new BufferedImage(width, height,
  50. BufferedImage.TYPE_INT_RGB);
  51. // 步骤二 图片绘制背景颜色 ---通过绘图对象
  52. Graphics graphics = bufferedImage.getGraphics();// 得到画图对象 --- 画笔
  53. // 绘制任何图形之前 都必须指定一个颜色
  54. graphics.setColor(getRandColor(200, 250));
  55. graphics.fillRect(0, 0, width, height);
  56. // 步骤三 绘制边框
  57. graphics.setColor(Color.WHITE);
  58. graphics.drawRect(0, 0, width - 1, height - 1);
  59. // 步骤四 四个随机数字
  60. Graphics2D graphics2d = (Graphics2D) graphics;
  61. // 设置输出字体
  62. graphics2d.setFont(new Font("宋体", Font.BOLD, 18));
  63. Random random = new Random();// 生成随机数
  64. int index = random.nextInt(words.size());
  65. String word = words.get(index);// 获得成语
  66. // 定义x坐标
  67. int x = 10;
  68. for (int i = 0; i < word.length(); i++) {
  69. // 随机颜色
  70. graphics2d.setColor(new Color(20 + random.nextInt(110), 20 + random
  71. .nextInt(110), 20 + random.nextInt(110)));
  72. // 旋转 -30 --- 30度
  73. int jiaodu = random.nextInt(60) - 30;
  74. // 换算弧度
  75. double theta = jiaodu * Math.PI / 180;
  76. // 获得字母数字
  77. char c = word.charAt(i);
  78. // 将c 输出到图片
  79. graphics2d.rotate(theta, x, 20);
  80. graphics2d.drawString(String.valueOf(c), x, 20);
  81. graphics2d.rotate(-theta, x, 20);
  82. x += 30;
  83. }
  84. // 将验证码内容保存session
  85. request.getSession().setAttribute("checkcode_session", word);
  86. // 步骤五 绘制干扰线
  87. graphics.setColor(getRandColor(160, 200));
  88. int x1;
  89. int x2;
  90. int y1;
  91. int y2;
  92. for (int i = 0; i < 30; i++) {
  93. x1 = random.nextInt(width);
  94. x2 = random.nextInt(12);
  95. y1 = random.nextInt(height);
  96. y2 = random.nextInt(12);
  97. graphics.drawLine(x1, y1, x1 + x2, x2 + y2);
  98. }
  99. // 将上面图片输出到浏览器 ImageIO
  100. graphics.dispose();// 释放资源
  101. //将图片写到response.getOutputStream()中
  102. ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
  103. }
  104. public void doPost(HttpServletRequest request, HttpServletResponse response)
  105. throws ServletException, IOException {
  106. doGet(request, response);
  107. }
  108. /**
  109. * 取其某一范围的color
  110. *
  111. * @param fc
  112. * int 范围参数1
  113. * @param bc
  114. * int 范围参数2
  115. * @return Color
  116. */
  117. private Color getRandColor(int fc, int bc) {
  118. // 取其随机颜色
  119. Random random = new Random();
  120. if (fc > 255) {
  121. fc = 255;
  122. }
  123. if (bc > 255) {
  124. bc = 255;
  125. }
  126. int r = fc + random.nextInt(bc - fc);
  127. int g = fc + random.nextInt(bc - fc);
  128. int b = fc + random.nextInt(bc - fc);
  129. return new Color(r, g, b);
  130. }
  131. }

3 实现点击动态改变

在这里插入图片描述

  1. <script type="text/javascript">
  2. function changeImg(obj) {
  3. obj.src="${pageContext.request.contextPath }/checkImg?time="+new Date().getTime();
  4. }
  5. </script>

4 实现验证码的校验功能

  1. package www.test.web.servlet;
  2. import java.io.IOException;
  3. import java.sql.SQLException;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import www.test.domain.User;
  9. import www.test.service.LoginService;
  10. public class LoginServlet extends HttpServlet {
  11. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  12. // 解决乱码问题
  13. request.setCharacterEncoding("UTF-8");
  14. // 获得页面输入的验证
  15. String checkCode_client = request.getParameter("checkCode");
  16. // 获得生成图片的文字的验证码
  17. String checkCode_session = (String) request.getSession().getAttribute("checkcode_session");
  18. // 比对页面的和生成图片的文字的验证码是否一致
  19. if (!checkCode_session.equals(checkCode_client)) {
  20. request.setAttribute("loginInfo", "您的验证码不正确");
  21. request.getRequestDispatcher("/login.jsp").forward(request, response);
  22. return; //验证码输入错误的话,就没有必要获取输入的用户名和密码
  23. }
  24. // 获取用户输入的数据
  25. String username = request.getParameter("username");
  26. String password = request.getParameter("password");
  27. LoginService service = new LoginService();
  28. User user = null;
  29. try {
  30. user = service.findUser(username, password);
  31. } catch (SQLException e) {
  32. e.printStackTrace();
  33. }
  34. if (user != null) {
  35. response.sendRedirect("/WEBTest24/index.jsp");
  36. } else {
  37. request.getRequestDispatcher("/login.jsp").forward(request, response);
  38. ;
  39. }
  40. }
  41. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  42. doGet(request, response);
  43. }
  44. }
  45. <div id="checkCodeInfo" style="color:red">${loginInfo}</div>

发表评论

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

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

相关阅读