AJAX(二)-实现验证码异步验证功能

案例实现效果

用户在前端输入验证码,按键收起触发异步验证,验证验证码的对错

前端代码

checkcode.jsp

  1. <%--  
  2.   Created by IntelliJ IDEA.  
  3.   User: cxspace  
  4.   Date: 16-8-18  
  5.   Time: 下午7:45  
  6.   To change this template use File | Settings | File Templates.  
  7. --%>  
  8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>  
  9. <html>  
  10. <head>  
  11.     <title>验证码检查</title>  
  12.     <script type="text/javascript" src="js/ajax.js"></script>  
  13. </head>  
  14. <body>  
  15.    <form>  
  16.        <table border="0" align="center">  
  17.            <th>验证码:</th>  
  18.            <td><input size="3" type="text" name="checkcode" id="checkcodeID" maxlength="4"/></td>  
  19.            <td><img src="check/checkImage.jsp" /></td>  
  20.            <td id="res"></td>  
  21.        </table>  
  22.    </form>  
  23.   
  24.    <script type="text/javascript">  
  25.   
  26.        //去掉两边空格  
  27.        function trim(str) {  
  28.            //正则表达式去掉左边空格  
  29.            str = str.replace(/^\s*/,""); //换掉左边空格  
  30.            str = str.replace(/\s*$/,"");  //换掉右边空格  
  31.            return str;  
  32.        }  
  33.   
  34.    </script>  
  35.   
  36.    <script type="text/javascript">  
  37.        document.getElementById("checkcodeID").onkeyup = function () {  
  38.   
  39.            var checkcode = this.value;  
  40.            var checkcode = trim(checkcode);  
  41.   
  42.            if (checkcode.length == 4){  
  43.                var ajax = createAJAX();  
  44.                var method = "POST";  
  45.                var url = "${pageContext.request.contextPath}/checkRequest?time="+new Date().getTime();  
  46.                ajax.open(method,url);  
  47.                ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");  
  48.                var content = "checkcode="+checkcode;  
  49.                ajax.send(content);  
  50.                ajax.onreadystatechange = function () {  
  51.                    if(ajax.readyState == 4){  
  52.                        if (ajax.status == 200){  
  53.                            var tip = ajax.responseText;  
  54.                            var img = document.createElement("img");  
  55.                            img.src = tip;  
  56.                            img.style.width = "14px";  
  57.                            img.style.height = "14px";  
  58.                            var td = document.getElementById("res");  
  59.                            td.innerHTML="";  
  60.                            td.appendChild(img)  
  61.                        }  
  62.                    }  
  63.                }  
  64.            }else {  
  65.   
  66.                var td = document.getElementById("res");  
  67.                td.innerHTML = "";  
  68.            }  
  69.        }  
  70.    </script>  
  71.   
  72. </body>  
  73. </html>  
<%--
  Created by IntelliJ IDEA.
  User: cxspace
  Date: 16-8-18
  Time: 下午7:45
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>验证码检查</title>
    <script type="text/javascript" src="js/ajax.js"></script>
</head>
<body>
   <form>
       <table border="0" align="center">
           <th>验证码:</th>
           <td><input size="3" type="text" name="checkcode" id="checkcodeID" maxlength="4"/></td>
           <td><img src="check/checkImage.jsp" /></td>
           <td id="res"></td>
       </table>
   </form>

   <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;
           var checkcode = trim(checkcode);

           if (checkcode.length == 4){
               var ajax = createAJAX();
               var method = "POST";
               var url = "${pageContext.request.contextPath}/checkRequest?time="+new Date().getTime();
               ajax.open(method,url);
               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;
                           var img = document.createElement("img");
                           img.src = tip;
                           img.style.width = "14px";
                           img.style.height = "14px";
                           var td = document.getElementById("res");
                           td.innerHTML="";
                           td.appendChild(img)
                       }
                   }
               }
           }else {

               var td = document.getElementById("res");
               td.innerHTML = "";
           }
       }
   </script>

</body>
</html>

ajax.jsp

  1. //创建AJAX异步对象,即XMLHttpRequest  
  2. function createAJAX(){  
  3.     var ajax = null;  
  4.     try{  
  5.         ajax = new ActiveXObject("microsoft.xmlhttp");  
  6.     }catch(e1){  
  7.         try{  
  8.             ajax = new XMLHttpRequest();  
  9.         }catch(e2){  
  10.             alert("你的浏览器不支持ajax,请更换浏览器");  
  11.         }  
  12.     }  
  13.     return ajax;  
  14. }  
//创建AJAX异步对象,即XMLHttpRequest
function createAJAX(){
    var ajax = null;
    try{
        ajax = new ActiveXObject("microsoft.xmlhttp");
    }catch(e1){
        try{
            ajax = new XMLHttpRequest();
        }catch(e2){
            alert("你的浏览器不支持ajax,请更换浏览器");
        }
    }
    return ajax;
}

checkImage.jsp

  1. <%--  
  2.   Created by IntelliJ IDEA.  
  3.   User: cxspace  
  4.   Date: 16-8-18  
  5.   Time: 下午5:39  
  6.   To change this template use File | Settings | File Templates.  
  7. --%>  
  8. <%@ page language="java" pageEncoding="UTF-8" %>  
  9. <%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>  
  10. <%!  
  11.   
  12.     //获取随机颜色值  
  13.     public Color getColor(){  
  14.   
  15.         Random random = new Random();  
  16.   
  17.         int r = random.nextInt(256);  
  18.   
  19.         int g = random.nextInt(256);  
  20.   
  21.         int b = random.nextInt(256);  
  22.   
  23.         Color color = new Color(r,g,b);  
  24.   
  25.         return color;  
  26.     }  
  27.   
  28.     //获取四位随机数连成的字符串  
  29.     public String getNum(){  
  30.   
  31.         String str = "";  
  32.   
  33.         Random random = new Random();  
  34.   
  35.         for(int i = 0 ; i < 4 ; i++){  
  36.             str += random.nextInt(10);  
  37.         }  
  38.   
  39.         return  str;  
  40.     }  
  41. %>  
  42.   
  43. <%  
  44.     //设置浏览器不缓存图片  
  45.     response.setHeader("pragma","mo-cache");  
  46.     response.setHeader("cache-control","no-cache");  
  47.     response.setDateHeader("expires",0);  
  48.   
  49.     //设置图片大小和背景  
  50.     BufferedImage image = new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB);  
  51.     //创建画笔对象  
  52.     Graphics g = image.getGraphics();  
  53.     g.setColor(new Color(200,200,200));  
  54.     g.fillRect(0,0,80,30);  
  55.   
  56.     for (int i = 0 ; i < 20 ; i++){  
  57.         Random random = new Random();  
  58.   
  59.         int x = random.nextInt(80);  
  60.         int y = random.nextInt(30);  
  61.         int x1 = random.nextInt(x+10);  
  62.         int y1 = random.nextInt(y+10);  
  63.   
  64.         //背景模糊线使用随机色  
  65.         g.setColor(getColor());  
  66.         g.drawLine(x,y,x+x1,y+y1);  
  67.     }  
  68.   
  69.     g.setFont(new Font("serif",Font.BOLD,16));  
  70.     g.setColor(Color.black);  
  71.     String checkNum = getNum();  
  72.   
  73.     //给字符串字符之间加空格  
  74.     StringBuffer sb = new StringBuffer();  
  75.     for (int i = 0 ; i < checkNum.length() ; i ++){  
  76.         sb.append(checkNum.charAt(i)+" ");  
  77.     }  
  78.     g.drawString(sb.toString(),10,20);  
  79.   
  80.     session.setAttribute("checkNum",checkNum);  
  81.   
  82.     ImageIO.write(image,"jpeg",response.getOutputStream());  
  83.     out.clear();  
  84.     out = pageContext.pushBody();  
  85. %>  
<%--
  Created by IntelliJ IDEA.
  User: cxspace
  Date: 16-8-18
  Time: 下午5:39
  To change this template use File | Settings | File Templates.
--%>
<%@ 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);

        Color color = new Color(r,g,b);

        return color;
    }

    //获取四位随机数连成的字符串
    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 < 20 ; 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,x+x1,y+y1);
    }

    g.setFont(new Font("serif",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(),10,20);

    session.setAttribute("checkNum",checkNum);

    ImageIO.write(image,"jpeg",response.getOutputStream());
    out.clear();
    out = pageContext.pushBody();
%>

后端代码

action配置

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <!DOCTYPE struts PUBLIC  
  4.         "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"  
  5.         "http://struts.apache.org/dtds/struts-2.3.dtd">  
  6.   
  7. <struts>  
  8.    <package name="myPackage" namespace="/" extends="struts-default">  
  9.   
  10.       <action name="checkRequest"  
  11.               class="checkcode.CheckcodeAction"  
  12.               method="check">  
  13.   
  14.       </action>  
  15.   
  16.    </package>  
  17.   
  18. </struts>  
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
   <package name="myPackage" namespace="/" extends="struts-default">

      <action name="checkRequest"
              class="checkcode.CheckcodeAction"
              method="check">

      </action>

   </package>

</struts>

checkcode.CheckcodeAction

  1. package checkcode;  
  2.   
  3. import com.opensymphony.xwork2.ActionContext;  
  4. import com.opensymphony.xwork2.ActionSupport;  
  5. import org.apache.struts2.ServletActionContext;  
  6.   
  7. import javax.servlet.http.HttpServletResponse;  
  8. import java.io.PrintWriter;  
  9.   
  10. /** 
  11.  * Created by cxspace on 16-8-18. 
  12.  */  
  13. public class CheckcodeAction extends ActionSupport{  
  14.   
  15.     private String checkcode;  
  16.   
  17.     public void setCheckcode(String checkcode) {  
  18.         this.checkcode = checkcode;  
  19.     }  
  20.   
  21.     public String check() throws Exception {  
  22.   
  23.         String tip = "images/MsgError.gif";  
  24.   
  25.         String checkcodeServer = (String) ActionContext.getContext().getSession().get("checkNum");  
  26.   
  27.         if (checkcode.equals(checkcodeServer)){  
  28.             tip="images/MsgSent.gif";  
  29.         }  
  30.   
  31.         HttpServletResponse response = ServletActionContext.getResponse();  
  32.   
  33.         response.setContentType("text/html;charset=UTF-8");  
  34.         PrintWriter pw = response.getWriter();  
  35.         pw.write(tip);  
  36.         pw.flush();  
  37.         pw.close();  
  38.   
  39.         return null;  
  40.     }  
  41. }  
package checkcode;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Created by cxspace on 16-8-18.
 */
public class CheckcodeAction extends ActionSupport{

    private String checkcode;

    public void setCheckcode(String checkcode) {
        this.checkcode = checkcode;
    }

    public String check() throws Exception {

        String tip = "images/MsgError.gif";

        String checkcodeServer = (String) ActionContext.getContext().getSession().get("checkNum");

        if (checkcode.equals(checkcodeServer)){
            tip="images/MsgSent.gif";
        }

        HttpServletResponse response = ServletActionContext.getResponse();

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.write(tip);
        pw.flush();
        pw.close();

        return null;
    }
}

  

  

 

 

  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值