生成图片验证码(前端+后台)

后台生成验证码 并存在session里面

@Service
public class imageYZM {

    public BufferedImage getimgYZM(HttpServletRequest request){
        BufferedImage bi = new BufferedImage(68,22,BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.getGraphics();//画笔对象
        Color c = new Color(200,150,255);//颜色对象
        g.setColor(c);//给画笔赋上颜色
        g.fillRect(0,0,430,30);//画一个外框
        char [] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
        Random r = new Random();
        int len = ch.length,index;
        StringBuffer sb = new StringBuffer();
        for (int i=0;i<4;i++){
            index = r.nextInt(len);
            g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255)));
            g.drawString(ch[index]+"",(i*15)+3,18);//画随机字符
            sb.append(ch[index]);
        }

        String checkCode = sb.toString(); 
        request.getSession().setAttribute("checkCode",checkCode);

        return bi;
//        ImageIO.write(bi,"JPG",response.getOutputStream());
    }
}

Controller

    @RequestMapping("/getCheckCode")
    public void getcheckcode(HttpServletResponse response,HttpServletRequest request)throws IOException{
        BufferedImage bi = imageyzm.getimgYZM(request);
        ImageIO.write(bi,"JPG",response.getOutputStream());
    }

前端

  <img src="getCheckCode" style="width: 80px; height: 30px;" alt="验证码"  id="checkcode"/>

JS文件

实现的是点击验证码就会向后台重新请求一次验证码

$(document).ready(function () {
    $('#checkcode').click(function () {
        $.ajax({
            url: 'getCheckCode',
            type: 'get',
            success: function (data, status, xhr) {
                $('#checkcode').attr('src', 'getCheckCode');
            },
        });
    });
});
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值