簡單的驗證碼點擊切換


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);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM