Java中使用servlet简单的实现验证码生成

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        int width = 100;
        int height = 50;

        // 1.创建一对象,在内存中图片(验证码图片对象)
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
       /*
            2.美化图片
       */
        Graphics graphics = image.getGraphics();
        // 2.1 填充背景色
        graphics.setColor(Color.pink); //设置画笔颜色
        graphics.fillRect(0, 0, width, height);  //填充背景色

        // 2.2 画边框
        graphics.setColor(Color.blue);
        graphics.drawRect(0, 0, width - 1, height - 1);
        // 定义随机值池
        String str = "ABCDEFGHQJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        // 生成随机角标
        Random ran = new Random();
        // 2.3 写入验证码
        for (int i = 0; i < 4; i++) {
            int index = ran.nextInt(str.length());
            // 获取随机字符
            char c = str.charAt(index);
            // 随机生成 x 轴
            int x = ran.nextInt(width - 10) % (width - 10 - 10 + 1) + 10;
            // 随机生成 Y 轴
            int y = ran.nextInt(height - 5) % (width - 5 - 5 + 1) + 5;
            graphics.drawString(c + "", x, y);
        }
        // 2.4 画干扰线
        graphics.setColor(Color.green);
        for (int i = 0; i < 10 ; i++) {
            int x1 = ran.nextInt(width);
            int x2 = ran.nextInt(width);
            int y1 = ran.nextInt(height);
            int y2 = ran.nextInt(height);
            graphics.drawLine(x1, y1, x2, y2);
        }

        // 3.将图片输出到页面
        ImageIO.write(image, "jpg", response.getOutputStream());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}

 

上一篇:【JAVA习题三十四】某个公司采用公用电话传递数据,数据是四位的整数,在传递过程中是加密的,加密规则如下:每位数字都加上5,然后用和除以10的余数代替该数字,再将第一位和第四位交换,第二位和第三位交换


下一篇:Java Scanner类的使用