java生成动态验证码

编写CheckImgServlet实现类

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

用于生成验证码图片上的文字如下下面四字成语,太多只打出一部分,你们可以自己添加,将其保存为txt文档,保存web项目的WEB-INF下

一唱一和
一呼百应
一干二净
一举两得
一落千丈
一模一样
一暴十寒
一日千里
一五一十
一心一意
两面三刀
三长两短
三番五次
三三两两
三头六臂
三心二意
三言两语

html.login文件,确定验证码显示的位置用于登陆页面

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

 

 
posted @ 2019-09-04 16:17  撑起一片阳光  阅读(1540)  评论(1编辑  收藏  举报