JavaWeb核心修炼手册10---验证码

1. 步骤

  1. 利用BufferedImage对象在内存中创建图片对象。
  2. 美化图片
    1. 获取画笔
    2. 设置颜色
    3. 填充背景色用fill/画图用draw
  3. 用ImageIO.write()方法传输图片

2. 效果

在这里插入图片描述

3. 代码

(1)ResponseServlet.java

@WebServlet("/responseServlet")
public class ResponseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 在内存中方创建图片对象
        int width = 200;
        int height = 100;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //2.美化图片
        //2.1 填充图片背景色
        Graphics g = image.getGraphics();      //获取画笔
        g.setColor(Color.PINK);
        g.fillRect(0, 0, width, height);
        //2.2 画矩形边框
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, width-1, height-1);
        //2.3 画文字
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            int index = random.nextInt(str.length());
            char c = str.charAt(index);
            g.setColor(Color.BLUE);
            g.drawString(c+"", width/5*(i+1), height/2);
        }
        //2.4 画干扰线
        for (int i = 0; i < 6; i++) {
            int x1 = random.nextInt(width);
            int x2 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int y2 = random.nextInt(height);
            g.setColor(Color.green);
            g.drawLine(x1, y1, x2, y2);
        }

        //3.传输图片
        ImageIO.write(image, "png", response.getOutputStream());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
        new Date();
    }
}

(2)regist.html




    
    Title
    


    
    看不清,换一张


你可能感兴趣的:(JavaWeb核心修炼手册10---验证码)