JAVA生成图片验证码、页面点击切换验证码图片

首先引入 easy-captcha-1.6.2-RELEASE.jar

1、生成字母验证码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //宽120 高40 4个字母 如:abGs
        SpecCaptcha captcha = new SpecCaptcha(120, 40, 4);
        //将验证码上的4个字母(Object 类型)存到session域
        request.getSession().setAttribute("pic", captcha.text());
        //将验证码响应给前端
        captcha.out(response.getOutputStream());
    }

2、生成计算式验证码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //验证码图片宽200 高40 四位运算 如:1+2+3+4=
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(200, 40, 4);
        //captcha.text()为计算式的计算结果
        request.getSession().setAttribute("pic", captcha.text());
        //响应验证码图片给前端
        captcha.out(response.getOutputStream());
    }

3、生成GIF验证码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //验证码图片宽120 高40 4个字母
        GifCaptcha captcha=new GifCaptcha(120, 40, 4);
        //将验证码的值(Object 类型)存到session域
        request.getSession().setAttribute("pic", captcha.text());
        //将图片响应给前端
        captcha.out(response.getOutputStream());
    }

4、生成汉字验证码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //由于验证码是汉字类型,所以需要设置编码格式
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //创建验证码对象
        ChineseCaptcha captcha=new ChineseCaptcha(120, 40, 4);
        request.getSession().setAttribute("pic", captcha.text());
        captcha.out(response.getOutputStream());
    }

5、生成汉字GIF验证码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //由于验证码是汉字类型,所以需要设置编码格式
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //创建验证码对象
        ChineseGifCaptcha captcha=new ChineseGifCaptcha(120, 40, 4);
        request.getSession().setAttribute("pic", captcha.text());
        captcha.out(response.getOutputStream());
    }

前端:验证码看不清,点击换一张

<form method="post" action="/get.do">
        <p>验证码:<input type="text" name="captcha">
            <img src="/ch" onclick="this.src='/ch?t='+Math.random()"/>
        </p>
        <input type="submit" value="提交">
</form>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值