Servlet随机数生成及验证码

创建CaptchaController

@WebServlet("/captcha")
public class CaptcheController extends HttpServlet {
    private final int WIDTH = 100;
    private final int HEIGHT = 60;
//图片的高宽度
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedImage img = new BufferedImage(100, 80, BufferedImage.TYPE_INT_RGB);//保存在缓冲区中的一张图片
        Graphics g = img.getGraphics();//创建图片对象
        g.setColor(Color.WHITE);//设置背景图片为白色
        g.fillRect(0, 0, WIDTH, HEIGHT);
        g.setFont(new Font("宋体", 20, 20 ));
        g.setColor(Color.red);
        drawRandomLine(g);
        String code=randomString((Graphics2D)g,4);
        g.drawString(code,20,30);
        g.dispose();
        ServletOutputStream out = resp.getOutputStream();
        ImageIO.write(img, "JPEG", out);
        try {
            out.flush();
        } catch (Exception ex) {
        } finally {
            out.close();
        }
    }

    private void drawRandomLine(Graphics g) {
        //设置颜色
        g.setColor(Color.black);
        //设置线条个数并画线
        for ( int i = 0 ; i < 4 ; i++ ) {
            int x1 = new Random().nextInt(WIDTH);
            int y1 = new Random().nextInt(HEIGHT);
            int x2 = new Random().nextInt(WIDTH);
            int y2 = new Random().nextInt(HEIGHT);
            g.drawLine(x1, y1, x2, y2);
        }
        g.setColor(Color.pink);
        for(int i = 0;i<100;i++){  //生成100个随机位置点
            Random ran = new Random();
            int x = ran.nextInt(WIDTH);
            int y = ran.nextInt(WIDTH);
            g.drawOval(x,y,1,1);
        }


    }

    public String randomString(Graphics2D g,int count) {
        StringBuilder builder = new StringBuilder();
        String source = "abcdefghijklmnpqrstuvwxy0123456789";
        Random rnd = new Random();
        for (int i = 0; i < count; i++) {
            int pos = rnd.nextInt(source.length());
            String s = source.substring(pos, pos + 1);
            builder.append(s);
            int x=5;
            int degree = new Random().nextInt() % 30;
            //正向角度
            g.rotate(degree  * Math.PI / 180 , x,20);
            g.drawString(s, x, 20);
            //反向角度
            g.rotate(-degree  * Math.PI / 180 , x,20);
            x+=30;

        }
        return builder.toString();
    }
}


测试检查随机数生成及验证码

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值