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

后台生成验证码 并存在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());
    }

前端

  验证码

JS文件

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

$(document).ready(function () {
    $('#checkcode').click(function () {
        $.ajax({
            url: 'getCheckCode',
            type: 'get',
            success: function (data, status, xhr) {
                $('#checkcode').attr('src', 'getCheckCode');
            },
        });
    });
});

你可能感兴趣的:(工具集)