查看: 1662|回复: 0

[Java代码] Servlet案例3:验证码功能

发表于 2018-3-3 12:05:59

这里介绍简单的验证码功能

动态生成图片

一个简单的页面:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Insert title here</title>
  6. <script type="text/javascript">
  7. function changeImg(obj){
  8. obj.src="/WEB4/checkImg?time="+new Date().getTime();
  9. }
  10. </script>
  11. </head>
  12. <body>
  13. <form action="/WEB13/login" method="post">
  14. 用户名:<input type="text" name="username"><br/>
  15. 密码:<input type="password" name="password"><br/>
  16. 验证码:<input type="text" name="username"><img onclick="changeImg(this)" src="/WEB4/checkImg"><br/>
  17. <input type="submit" value="登录"><br/>
  18. </form>
  19. </body>
  20. </html>
复制代码
View Code

简单的JS代码实现点击验证码图片刷新

验证码功能:

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

这里采用的是成语的验证码,将很多个成语存到WEB-INF目录下一个文本中,每行一个即可

补上web.xml配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  3. <display-name>WEB4</display-name>
  4. <welcome-file-list>
  5. <welcome-file>index.html</welcome-file>
  6. <welcome-file>index.htm</welcome-file>
  7. <welcome-file>index.jsp</welcome-file>
  8. <welcome-file>default.html</welcome-file>
  9. <welcome-file>default.htm</welcome-file>
  10. <welcome-file>default.jsp</welcome-file>
  11. </welcome-file-list>
  12. <servlet>
  13. <description></description>
  14. <display-name>CheckImgServlet</display-name>
  15. <servlet-name>CheckImgServlet</servlet-name>
  16. <servlet-class>demo.CheckImgServlet</servlet-class>
  17. </servlet>
  18. <servlet-mapping>
  19. <servlet-name>CheckImgServlet</servlet-name>
  20. <url-pattern>/checkImg</url-pattern>
  21. </servlet-mapping>
  22. </web-app>
复制代码
View Code



回复

使用道具 举报