简单的验证码点击切换

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>验证码</title>
    <script>
        var code
        window.onload=function () {
            code=document.getElementById("checkCode");
            code.onclick=change();
        }
        function change() {
            var time=new Date().getTime();
            code.src="/day07/ServletCheckCode?"+time;
        }

    </script>
</head>
<body>
    <img id="checkCode" src="/day07/ServletCheckCode">
    <a onclick="change() " href="javascript:void(0)">看不清楚?点击换一张</a>
</body>
</html>

servlet

@WebServlet("/ServletCheckCode")
public class ServletCheckCode extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1创建对象
        int width=100;
        int height=50;
        BufferedImage img=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //2.美化图片
        //填充背景色
        Graphics g=img.getGraphics();
        g.setColor(Color.pink);
        g.fillRect(0,0,width,height);

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

        //写验证码
        String str="QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm0123456789";
        Random ran=new Random();
        for (int i = 1; i <= 4; i++) {
            int index = ran.nextInt(str.length());
            char c = str.charAt(index);
            g.drawString(c+"",width/5*i,height/2);
        }
        //画干扰线
        g.setColor(Color.green);
        int x1;
        int y1;
        int x2;
        int y2;
        for (int i = 0; i <10; i++) {
            x1=ran.nextInt(width);
            x2=ran.nextInt(width);
            y1=ran.nextInt(height);
            y2=ran.nextInt(height);
            g.drawLine(x1,y1,x2,y2);
        }
        //3.展示图片
        ImageIO.write(img,"jpg",response.getOutputStream());
    }

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

猜你喜欢

转载自www.cnblogs.com/findlisa/p/10873291.html