如何在js中加入验证码。

图片说明这是负责前台的同事发来的。我在网上找到了一个例子。通过VerifyCodeServlet调用
VerifyCode工具类生成验证码。
图片说明
例子中是通过这段代码在html中加入验证码图片,我尝试把图一中src后面改为VerifyCodeServlet没有作用。
图片说明
想要达到这种效果

https://www.cnblogs.com/suxiaoxia/p/6834119.html
去看看这篇文章吧

通过session写验证码

动态页注意设置好content-type为image/png之类的,并且输出2进制数据流

直接浏览器打开src的地址看能正常显示图片没有,没有就是你动态页有问题

不说了,直接看代码:
//修改验证码的组成,验证码全为纯数字
public String getRandom() {

try {

int width = 50;

int height = 18;

// 取得一个4位随机字母数字字符串

String s = RandomStringUtils.random(4, true, true);

//去除里面的大小写字母,以后验证码由纯字母组成
s = RandomStringUtils.random(4,new char[] {'1', '2', '3', '4', '5', '6', '7', '8', '9' });
// 保存入session,用于与用户的输入进行比较.

// 注意比较完之后清除session.

HttpSession session = request.getSession(true);

session.setAttribute("randomAuthCode", s);

        response.setContentType("images/jpeg");  
        response.setHeader("Pragma", "No-cache");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setDateHeader("Expires", 0);  

        ServletOutputStream out = response.getOutputStream();  
        BufferedImage image = new BufferedImage(width, height,  
                BufferedImage.TYPE_INT_RGB);  
        Graphics g = image.getGraphics();  
        // 设定背景色  

// g.setColor(getRandColor(200, 250));

g.setColor(Color.white);

g.fillRect(0, 0, width, height);

        // 设定字体  
        Font mFont = new Font("Verdana", Font.PLAIN, 17);// 设置字体  
        g.setFont(mFont);  

        // 画边框  
        // g.setColor(Color.BLACK);  
        // g.drawRect(0, 0, width - 1, height - 1);  

        // 随机产生干扰线,使图象中的认证码不易被其它程序探测到  

// g.setColor(getRandColor(160, 200));

CreateRandomPoint(width,height,30,g,255);
// 生成随机类

// Random random = new Random();

// for (int i = 0; i < 155; i++) {

// int x2 = random.nextInt(width);

// int y2 = random.nextInt(height);

// int x3 = random.nextInt(12);

// int y3 = random.nextInt(12);

// g.drawLine(x2, y2, x2 + x3, y2 + y3);

// }

        // 将认证码显示到图象中  
        g.setColor(Color.black);  

// g.setColor(new Color(20 + random.nextInt(110), 20 + random

// .nextInt(110), 20 + random.nextInt(110)));

        g.drawString(s, 2, 16);  

        // 图象生效  
        g.dispose();  
        // 输出图象到页面  
        ImageIO.write((BufferedImage) image, "JPEG", out);  
        out.close();  
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
    return null;  
}  

根据servlet来 构建前台的 图形验证码 输入后返回后台 验证

使用canvas去做不需要服务端传输流效率更高