【JavaWeb】实现网页验证码

本文介绍了在JavaWeb中实现验证码的方法,包括字母数字验证码、算术验证码的生成,并详细讲解了如何使用Kaptcha框架来简化验证码的创建过程。同时,文章还涵盖了验证码的字符串校验,包括客户端和服务器端的验证逻辑。
摘要由CSDN通过智能技术生成

导读:常用的验证码有文本+数字,或者是算式验证码。可以自己编写,来生成验证码。亦或是使用第三方库,来生成验证码。


字母数字验证码

实现形如下图的验证码:

                                                                

编写一个验证码生成类,首先写一个产生随机字符的方法:

public class CaptchaCode {
    private static char randomChar(){
        String string="QWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        Random random=new Random();
        return string.charAt(random.nextInt(string.length()));
    }
}

然后写一个生成验证码图片的方法:

    public static String drawImage(HttpServletResponse response){
        //1.拼接字符串的类
        StringBuilder builder=new StringBuilder();
        //产生4位验证码
        for (int i = 0; i <4 ; i++) {
            builder.append(randomChar());
        }
        String code=builder.toString();
        //2.定义图片的宽度和高度
        int width=120;
        int height=25;
        //建立BufferedImage对象,指定图片缓冲流的长宽度和样式
        BufferedImage bi=new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
        //3.获取Graphics2d绘制对象,开始绘制验证码。图片最终会注入到缓冲流中
        Graphics2D graph=bi.createGraphics();
        //4.设置字体和大小
        Font font=new Font("宋体",Font.PLAIN,20);
        Color color=new Color(0,255,255);
        graph.setFont(font);
        graph.setColor(color);
        graph.setBackground(new Color(0,0,0));
        //绘制形状,一般是矩形
        graph.clearRect(0,0,width,height);
        //创建字体对象
        FontRenderContext context=graph.getFontRenderContext();
        //获得文字的边界
        Rectangle2D bounds=font.getStringBounds(code,context);
        //计算坐标和间距,以便字体放在矩形的正中央
        double x=(width-bounds.getWidth())/2;
        double y=(height-bounds.getHeight())/2;
        double acsent=bounds.getY();
        double baseY=y-acsent;
        //在矩形中绘制字体
        graph.drawString(code,(int)x,(int)baseY);
        graph.dispose();
        //保存到响应的输出流
        try {
            ImageIO.write(bi,"jpg",response.getOutputStream());
            //刷新响应流
            response.flushBuffer();
        } catch (IOException e) {
    
  • 5
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值