Web学习之简单验证码的实现(Servlet)

刚刚进行完了接近两周时间的课设, 我们选择的是做一个web版的项目,而事实上整个团队之前都从没接触过web方面的知识,整个过程不可谓不煎熬。
从最初的一无所知到后面的初步能上手,有许多需要记录总结的知识,就从验证码开始吧。


对于Web项目,验证码几乎是必备的,例如登陆功能就要用到,以防止恶意用户进行不断的登陆尝试。
那么验证码应该如何实现呢。
很简单,在后台,随机产生一串数字或文本,将其以图片形式展示在前端,再将用户输入的验证码内容与后台原本的内容进行对比来验证。

后台部分

import *;//导入库部分省略

@WebServlet("/image.show")
public class Image extends HttpServlet{

    //随机产生一种颜色
    Color getRandColor(int fc, int bc)
    {
        Random random = new Random();
        if(fc>255) fc=255;
        if(bc>255) bc=255;
        int r=fc+random.nextInt(bc-fc);
        int g=fc+random.nextInt(bc-fc);
        int b=fc+random.nextInt(bc-fc);
        return new Color(r,g,b);
    }


    public void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        //创建图像
        int width = 60, height = 20;
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //获取图形
        Graphics g = image.getGraphics();

        Random random = new Random();
        g.setColor(getRandColor(200, 250));
        g.fillRect(0, 0, width, height);
        g.setFont(new Font("Times New Roman",Font.PLAIN,18));
        g.setColor(getRandColor(160, 200));
        //对图片进行模糊处理
        for(int i=0;i<155;i++)
        {
            int x=random.nextInt(width);
            int y=random.nextInt(height);
            int x1=random.nextInt(12);
            int y1=random.nextInt(12);
            g.drawLine(x, y, x+x1, y+y1);
        }
        //写入验证码
        String sRand="";
        for(int i=0; i<4; i++)
        {
            String rand=String.valueOf(random.nextInt(10));
            sRand+=rand;
            g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
            g.drawString(rand, 13*i+6, 16);
        }

        Check_num.check_num = sRand;//用一静态变量记录验证码,用以后面的验证
        g.dispose();//释放图片资源
        ImageIO.write(image, "JPEG",response.getOutputStream());//将图片发送到前端
    }
}

前端部分(很简单,向后台请求获取图片显示即可)

<!DOCTYPE html>
<html>
<head>
    <title>check</title>
</head>
<body>
    <img src="image.show">
</body>
</html>

效果展示

这里写图片描述


Web学习之简单验证码的实现(Servlet)
https://shiyi.threebody.xyz/posts/63605.html
作者
Yi Shi
发布于
2016年6月23日
许可协议