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

时间:2020-12-26 05:22:44

案例实现效果

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

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

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. <script type="text/javascript">
  24. //去掉两边空格
  25. function trim(str) {
  26. //正则表达式去掉左边空格
  27. str = str.replace(/^\s*/,""); //换掉左边空格
  28. str = str.replace(/\s*$/,"");  //换掉右边空格
  29. return str;
  30. }
  31. </script>
  32. <script type="text/javascript">
  33. document.getElementById("checkcodeID").onkeyup = function () {
  34. var checkcode = this.value;
  35. var checkcode = trim(checkcode);
  36. if (checkcode.length == 4){
  37. var ajax = createAJAX();
  38. var method = "POST";
  39. var url = "${pageContext.request.contextPath}/checkRequest?time="+new Date().getTime();
  40. ajax.open(method,url);
  41. ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
  42. var content = "checkcode="+checkcode;
  43. ajax.send(content);
  44. ajax.onreadystatechange = function () {
  45. if(ajax.readyState == 4){
  46. if (ajax.status == 200){
  47. var tip = ajax.responseText;
  48. var img = document.createElement("img");
  49. img.src = tip;
  50. img.style.width = "14px";
  51. img.style.height = "14px";
  52. var td = document.getElementById("res");
  53. td.innerHTML="";
  54. td.appendChild(img)
  55. }
  56. }
  57. }
  58. }else {
  59. var td = document.getElementById("res");
  60. td.innerHTML = "";
  61. }
  62. }
  63. </script>
  64. </body>
  65. </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. public Color getColor(){
  13. Random random = new Random();
  14. int r = random.nextInt(256);
  15. int g = random.nextInt(256);
  16. int b = random.nextInt(256);
  17. Color color = new Color(r,g,b);
  18. return color;
  19. }
  20. //获取四位随机数连成的字符串
  21. public String getNum(){
  22. String str = "";
  23. Random random = new Random();
  24. for(int i = 0 ; i < 4 ; i++){
  25. str += random.nextInt(10);
  26. }
  27. return  str;
  28. }
  29. %>
  30. <%
  31. //设置浏览器不缓存图片
  32. response.setHeader("pragma","mo-cache");
  33. response.setHeader("cache-control","no-cache");
  34. response.setDateHeader("expires",0);
  35. //设置图片大小和背景
  36. BufferedImage image = new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB);
  37. //创建画笔对象
  38. Graphics g = image.getGraphics();
  39. g.setColor(new Color(200,200,200));
  40. g.fillRect(0,0,80,30);
  41. for (int i = 0 ; i < 20 ; i++){
  42. Random random = new Random();
  43. int x = random.nextInt(80);
  44. int y = random.nextInt(30);
  45. int x1 = random.nextInt(x+10);
  46. int y1 = random.nextInt(y+10);
  47. //背景模糊线使用随机色
  48. g.setColor(getColor());
  49. g.drawLine(x,y,x+x1,y+y1);
  50. }
  51. g.setFont(new Font("serif",Font.BOLD,16));
  52. g.setColor(Color.black);
  53. String checkNum = getNum();
  54. //给字符串字符之间加空格
  55. StringBuffer sb = new StringBuffer();
  56. for (int i = 0 ; i < checkNum.length() ; i ++){
  57. sb.append(checkNum.charAt(i)+" ");
  58. }
  59. g.drawString(sb.toString(),10,20);
  60. session.setAttribute("checkNum",checkNum);
  61. ImageIO.write(image,"jpeg",response.getOutputStream());
  62. out.clear();
  63. out = pageContext.pushBody();
  64. %>
<%--
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 &lt; 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 &lt; 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 &lt; 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. <!DOCTYPE struts PUBLIC
  3. "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
  4. "http://struts.apache.org/dtds/struts-2.3.dtd">
  5. <struts>
  6. <package name="myPackage" namespace="/" extends="struts-default">
  7. <action name="checkRequest"
  8. class="checkcode.CheckcodeAction"
  9. method="check">
  10. </action>
  11. </package>
  12. </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">
  &lt;action name="checkRequest"
class="checkcode.CheckcodeAction"
method="check"&gt; &lt;/action&gt;

</package>

</struts>

checkcode.CheckcodeAction

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

    }

    }