Fork me on GitHub

servlet实现动态验证码

 1 package com.dream.servlet;
 2 
 3 import javax.imageio.ImageIO;
 4 import javax.servlet.ServletException;
 5 import javax.servlet.annotation.WebServlet;
 6 import javax.servlet.http.HttpServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 import java.awt.*;
10 import java.awt.image.BufferedImage;
11 import java.io.IOException;
12 import java.util.Random;
13 
14 /**
15  * @author ZhangJun
16  * @date 2020-04-08
17  * @description 服务器向客户端输出字节数据
18  */
19 @WebServlet("/checkCodeServlet")
20 public class CheckCodeServlet extends HttpServlet {
21     @Override
22     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
23         this.doPost(req, resp);
24     }
25 
26     @Override
27     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
28         int width=100;
29         int height=50;
30         //1.创建一个对象,在内存中代表一个图片【验证码的图片对象】
31         BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
32 
33 
34         //2.美化图片
35         //2.1填充背景色 fillRect【填充】
36         Graphics graphics = image.getGraphics();
37         graphics.setColor(Color.PINK);//设置画笔颜色
38         graphics.fillRect(0,0,width, height);
39 
40         //2.2画边框 drawRect【画线条】
41         graphics.setColor(Color.BLUE);
42         graphics.drawRect(0, 0, width-1, height-1);
43 
44         String str ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
45         //生成随机角标
46         Random random = new Random();
47         for (int i = 1; i <=4; i++) {
48             int index = random.nextInt(str.length());
49             //获取字符
50             char cha = str.charAt(index);
51             //2.3写验证码
52             graphics.drawString(cha+"", width/5*i, height/2);
53         }
54         //2.4画干扰线
55         graphics.setColor(Color.green);
56         for (int i = 0; i < 10; i++) {
57             //随机生成坐标点
58             int x1 = random.nextInt(width);
59             int x2 = random.nextInt(width);
60             int y1 = random.nextInt(height);
61             int y2=  random.nextInt(height);
62             graphics. drawLine(x1, y1, x2, y2);
63         }
64 
65         //3.将图片输出到界面展示:使用ImageIO对象
66         //resp.getOutputStream() : 输出到页面,浏览器上
67         ImageIO.write(image, "jpg", resp.getOutputStream());
68     }
69 }

 

posted @ 2020-04-08 18:02  CodeZhangJ  阅读(16)  评论(0)    收藏  举报