自己用servlet实现0-9验证码,并且点击刷新,但是不建议还用,可以直接使用jar包自动生成
详情请见:servlet实现验证码

实现类

public class Demo extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
  
        code();
    }

    
    private void code HttpServletResponse response) throws IOException {
        int width = 110;
        int height = 25;
        //在内存中创建一个图像对象
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        
        //创建一个画笔
        Graphics g = img.getGraphics();
        
        //给图片添加背景色
        g.setColor(Color.PINK);//设置一个颜色
        g.fillRect(1, 1, width-2, height-2);//填充颜色
        
        //给边框一个色
        g.setColor(Color.RED);
        g.drawRect(0, 0, width-1, height-1);//设置边框的显示坐标
        
        //设置文本样式
        g.setColor(Color.BLUE);
        g.setFont(new Font("宋体", Font.BOLD|Font.ITALIC, 15));
        
        //给图片添加文本
        Random rand = new Random();
        int position = 20;
        for (int i = 0; i < 4; i++) {
            g.drawString(rand.nextInt(10)+"", position, 20);//给图片填充文本
            position+=20;
        }
        
        //添加9条干扰线
        for (int i = 0; i < 9; i++) {
            g.drawLine(rand.nextInt(width), rand.nextInt(height), rand.nextInt(width), rand.nextInt(height));
        }
        //将图片对象以流的方式输出的客户端
        ImageIO.write(img, "jpg", response.getOutputStream());
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

网页代码

<script type="text/javascript">
    function changeCode(){
        //得到图片元素
        var img = document.getElementsByTagName("img")[0];
        //img.setAttribute("src","/day09_00_HttpServletResponse/servlet/demo");//XML Dom 语法
        img.src = "/day09_00_HttpServletResponse/servlet/demo?time="+new Date().getTime();
    }
</script>
<img src="/day09_00_HttpServletResponse/servlet/demo4" onclick="changeCode()"/>
<a href="javascript:changeCode()" >看不清换一张</a>
Last modification:February 6, 2018
If you think my article is useful to you, please feel free to appreciate