国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > AJAX > 正文

基于ajax實現驗證碼功能

2024-09-01 08:30:28
字體:
來源:轉載
供稿:網友

我們在開發程序的時候,都有一個驗證碼的功能,但是程序員開發的時候要怎么實現呢?下面就讓錯新技術頻道小編帶大家一起來看看基于ajax實現驗證碼功能的詳細介紹吧。

具體內容如下

首先創建一個驗證碼:

<%@ page contentType="image/jpeg; charset=utf-8"   language="java" import="java.util.*,java.awt.*,java.awt.image.*,javax.imageio.*"   pageEncoding="UTF-8"%> <!-- 以上導入awt和awt.image包 --> <%!   //獲取隨機顏色   public Color getColor(){    Random random = new Random();    //使用rgb()隨機產生顏色    int r = random.nextInt(256);    int g = random.nextInt(256);    int b = random.nextInt(256);        return new Color(r,g,b);   }      //獲取隨機數字 產生一個4位數   public String getNum(){    String str = "";    Random random = new Random();    for(int i = 0;i < 4;i++){     str += random.nextInt(10); //0-9    }    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 x1 = random.nextInt(x + 10);    int y1 = random.nextInt(y + 10);    //設置隨機顏色    g.setColor(getColor());    //畫出來    g.drawLine(x, y, x1, y1);   }      //字的顏色和數字   g.setFont(new Font("Microsoft YaHei",Font.BOLD,16));   g.setColor(Color.BLACK);   //獲取隨機數字   String checkNum = getNum();      //給字拼接空格   StringBuffer sb = new StringBuffer();   for(int i = 0;i < checkNum.length();i++){    sb.append(checkNum.charAt(i) + " ");   }   //畫出數字   g.drawString(sb.toString(), 15, 20);   //存入session域中   session.setAttribute("CHECKNUM", checkNum); //例如1010   //將圖像以jpeg的形式通過字節流輸出   ImageIO.write(image, "jpeg", response.getOutputStream());   //清除緩存   out.clear();   //放入body中   out = pageContext.pushBody(); %> 

將驗證碼壓縮成圖片,在checkcode.jsp中引用,并在該頁面中利用ajax向服務器發送數據

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html>  <head>  <base href="<%=basePath%>" rel="external nofollow" >    <title>驗證碼</title>    <meta http-equiv="pragma" content="no-cache">  <meta http-equiv="cache-control" content="no-cache">  <meta http-equiv="expires" content="0">   <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  <meta http-equiv="description" content="This is my page">  <style type="text/css">   table{    margin: 100px auto;   }     </style>  </head>   <body>   <table border="0" align="center">    <tr>     <td>驗證碼</td>     <td><input type="text" name="checkcode" id="checkcodeID" maxlength="4" size="4"></td>     <td><img alt="加載失敗" src="image.jsp"></td>     <td id="show">√√√</td>    </tr>   </table>  </body>  <script type="text/javascript">   //去除空格   function trim(str){    //從左側開始替換空格    str = str.replace(/^/s*/,"");    //從左側開始替換空格    str = str.replace(//s$/,"");    return str;   }    </script>   <script type="text/javascript">   //創建ajax對象   function createAjax(){    var ajax = null;    try{     ajax = new ActiveXObject("microsoft.xmlhttp");    }catch(e){     try{      ajax = new XMLHttpRequest();     }catch(e1){      alert("請更換瀏覽器");     }    }    return ajax;   }  </script>    <script type="text/javascript">   document.getElementById("checkcodeID").onkeyup = function(){    var checkcode = this.value;    //去除空格    checkcode = trim(checkcode);    if(checkcode.length == 4){     //獲取ajax對象     var ajax = createAjax();     //獲取去空格的內容          var method = "POST";     var url = "${pageContext.request.contextPath}/CheckcodeServlet?time="+new Date().getTime();     //準備發送異步請求     ajax.open(method, url);     //設置請求頭POST提交方式才需要     ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");     //拼接實體內容     var content = "checkcode=" + checkcode;         //發送請求     ajax.send(content);          //監聽服務器狀態變化     ajax.onreadystatechange = function(){      if(ajax.readyState == 4){       if(ajax.status == 200){        //獲取服務器內容        var tip = ajax.responseText;        //獲取圖片路徑 然后進行放入td中        var img = document.createElement("img");        img.src = tip;        img.style.width = "14px";        img.style.height = "14px";        var td = document.getElementById("show");        td.innerHTML = "";        td.appendChild(img);       }      }     }         }       }  </script> </html> 

然后編寫服務端,接收輸入的信息,判斷是否與驗證碼相互匹配,將對應的圖片的路徑以輸出流的方式輸出

public class CheckcodeServlet extends HttpServlet {  @Override  protected void doPost(HttpServletRequest req, HttpServletResponse resp)    throws ServletException, IOException {   req.setCharacterEncoding("utf-8");   resp.setContentType("text/html;charset=utf-8");   //圖片路徑   String tip = "images/MsgError.gif";      String checkcode = req.getParameter("checkcode");   //測試   System.out.println(checkcode);   //獲取session域中的數字   String checkcodeService = (String) req.getSession().getAttribute("CHECKNUM");   //判斷   if (checkcode.equals(checkcodeService)) {    tip = "images/MsgSent.gif";   }   //輸出路徑   PrintWriter pw = resp.getWriter();   pw.write(tip);   pw.flush();   pw.close();  } } 

當輸入第4個數字的時候就會出現提示
運行結果:

以上就是由錯新技術頻道小編帶來的基于ajax實現驗證碼功能?看完上述的介紹,相信大家已經學會了,錯新技術頻道會繼續為大家提供專業的知識。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 彭山县| 黄平县| 韶山市| 腾冲县| 博客| 姚安县| 宜宾县| 龙口市| 广德县| 绿春县| 略阳县| 托里县| 张家界市| 游戏| 扎鲁特旗| 大连市| 汾阳市| 顺义区| 玉林市| 南城县| 化德县| 泰州市| 中超| 赤水市| 绥棱县| 始兴县| 永靖县| 四平市| 建湖县| 壤塘县| 宁陕县| 肇庆市| 梅州市| 石门县| 苍梧县| 新巴尔虎右旗| 西丰县| 绍兴县| 文昌市| 察雅县| 临西县|