AJAX方式進行驗證碼的判斷(JS方式)


1.生成驗證碼

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page contentType="image/jpeg"  import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
<%!
    public Color getColor(){
        Random random = new Random();
        int r = random.nextInt(256);
        int g = random.nextInt(256);
        int b = random.nextInt(256);
        return new Color(r,g,b);
    }
    public String getNum(){
        String str = "";
        Random random = new Random();
        for(int i=0;i<4;i++){
            str += random.nextInt(10);
        }
        return str;
    }
%>
<%
    response.setHeader("pragma", "mo-cache");
    response.setHeader("cache-control", "no-cache");
    response.setDateHeader("expires", 0);
    
    BufferedImage image = new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB);
    
    Graphics g = image.getGraphics();
    g.setColor(new Color(200,200,200));
    g.fillRect(0,0,80,30);
    
    
    for (int i = 0; i < 30; i++) {
        Random random = new Random();
        int x = random.nextInt(80);
        int y = random.nextInt(30);
        int xl = random.nextInt(x+10);
        int yl = random.nextInt(y+10);
        g.setColor(getColor());
        g.drawLine(x, y, x + xl, y + yl);
    }
    
    
    g.setFont(new Font("serif", Font.BOLD,16));
    g.setColor(Color.BLACK);
    String checkNum = getNum();//"2525"
    
    StringBuffer sb = new StringBuffer();
    for(int i=0;i<checkNum.length();i++){
        sb.append(checkNum.charAt(i)+" ");//"2 5 2 5"
    }
    g.drawString(sb.toString(),15,20);
    
    session.setAttribute("CHECKNUM",checkNum);//2525
    
    ImageIO.write(image,"jpeg",response.getOutputStream());
    out.clear();
    out = pageContext.pushBody();
%>

2.添加驗證碼

<tr>
                <th>驗證碼:</th>
                <td><input size="2" type="text" name="checkcode" id="checkcodeID" maxlength="4"/></td>
                <td id="checked" ><img id="imageId" src="${pageContext.request.contextPath }/jsp/01_image.jsp"/>
                <td id="response"></td>
            </tr>

3.創建AJAX

function createAJAX(){
        var ajax = null;
        try{
            ajax = new ActiveXObject("microsoft.xmlhttp");
        }catch(e1){
            try{
                ajax = new XMLHttpRequest();
            }catch(e2){
                alert("你的瀏覽器不支持ajax!");
            }
        }
        return ajax;
    }

4.異步方式進行驗證

<!-- 去除空格 -->
  <script type="text/javascript">
        //去掉二邊的空格
        function trim(str){
            str = str.replace(/^\s*/,"");
            str = str.replace(/\s*$/,"");
            return str;     
        }
    </script>
<!-- 異步判斷驗證碼輸入是否正確 -->    
  <script type="text/javascript">
        document.getElementById("checkcodeID").onkeyup = function(){
            var checkcode = this.value;
            checkcode = trim(checkcode);
            if(checkcode.length == 4){
                //NO1)創建AJAX
                var ajax = createAJAX();
                //NO2)設置提交方式
                var method = "POST";
                var url = "${pageContext.request.contextPath}/dictionary_checked?time="+new Date().getTime();
                ajax.open(method,url);
                //NO3)設置請求頭
                ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
                //NO4)設置參數
                var content = "checkcode=" + checkcode;
                ajax.send(content);
            
                //--------------------------------------------------------等待
                
                //NO5)判斷是否返回成功並接收參數
                ajax.onreadystatechange = function(){
                    if(ajax.readyState == 4){
                        if(ajax.status == 200){
                            //NO6)
                            var tip = ajax.responseText;
                            
                            //NO7)
                            var img = document.createElement("img");
                            img.src = tip;
                            img.style.width = "14px";
                            img.style.height = "14px";
                            var td = document.getElementById("response");
                            td.innerHTML = "";
                            td.appendChild(img);
                        }
                    }
                }
            }else{
                //清空圖片
                var td = document.getElementById("response");
                td.innerHTML = "";
            }
        }
    </script>    

5.后台驗證

/**
     * 驗證
     */
    public String checked() throws Exception {
        // 圖片路徑
        String tip = "images/error.gif";
        // 從服務器獲取session中的驗證碼
        String checkcodeServer = (String) ActionContext.getContext()
                .getSession().get("CHECKNUM");
        // 將客戶端的驗證碼與服務端的驗證碼進行比較
        if (checkcode.equals(checkcodeServer)) {
            tip = "images/success.gif";
        }
        // 以IO流的方式將tip變量的值輸出到AJAX異步對象中
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.write(tip);
        pw.flush();
        pw.close();
        return null;
    }

6.提交驗證

function submit2(){
            //獲取js對象
            var td = document.getElementById("response");
            var img=td.firstChild;
            //獲取路徑信息
            var src2=img.src;
            //對輸入的結果進行判定,選擇是否提交
            if(src2==""){
                alert("驗證碼不能為空!");
            }else if(src2=="http://localhost:8080/BBS/jsp/images/success.gif"){
                var for2=document.forms[0];
                for2.submit();
            }else{
                alert("驗證碼輸入錯誤!");
            }
        }
    </script>

7.總結:

(1)暫時無法實現點擊更換驗證碼

(2)js方式過於繁瑣,代碼臃腫;


免責聲明!

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



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