AJAX(二)-实现验证码异步验证功能
案例实现效果
用户在前端输入验证码,按键收起触发异步验证,验证验证码的对错
前端代码
checkcode.jsp
- <%--
- 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>
<%--
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
- //创建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;
- }
//创建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
- <%--
- 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();
- %>
<%--
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配置
- <?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>
<?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
- 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;
- }
- }
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;
}
}
AJAX(二)-实现验证码异步验证功能的更多相关文章
- MVC验证09-使用MVC的Ajax.BeginForm方法实现异步验证
原文:MVC验证09-使用MVC的Ajax.BeginForm方法实现异步验证 MVC中,关于往后台提交的方法有: 1.Html.BeginForm():同步 2.Ajax.BeginForm():异 ...
- Thinkphp验证码异步验证第二次及以后验证,验证错误----待解决
今天进行差错时遇到的问题.别人的回答----链接(http://www.thinkphp.cn/topic/28968.html) 3.2.3版本里的check方法会在第一次验证正确后清除SESSIO ...
- formValidator输入验证、异步验证实例 + licenseImage验证码插件实例应用
实例技术:springmvc 实现功能:完整用户登录流程.输入信息规则校验.验证码异步校验. 功能清单: 1.springmvc控制器处理get请求(/member/login.html),进行静态页 ...
- MVC验证11-对复杂类型使用jQuery异步验证
原文:MVC验证11-对复杂类型使用jQuery异步验证 本篇体验使用"jQuery结合Html.BeginForm()"对复杂类型属性进行异步验证.与本篇相关的"兄弟篇 ...
- MVC验证10-到底用哪种方式实现客户端服务端双重异步验证
原文:MVC验证10-到底用哪种方式实现客户端服务端双重异步验证 本篇将通过一个案例来体验使用MVC的Ajax.BeginForm或jQuery来实现异步提交,并在客户端和服务端双双获得验证.希望能梳 ...
- 利用js制作异步验证ajax方法()
如何利用js写ajax异步验证.代码如下: window.onload = function(){ var name = document.getElementById('register-name- ...
- Ajax实现验证码异步校验
验证码异步校验可以防止表单提交后因验证码不正确导致已填的其它项都清空. 整个过程图如下 验证码输入框出代码 <div class="form-group"> <l ...
- 【java项目实践】具体解释Ajax工作原理以及实现异步验证username是否存在+源代码下载(java版)
一年前,从不知道Ajax是什么,伴随着不断的积累,到如今常常使用,逐渐有了深入的认识. 今天,假设想开发一个更加人性化,友好,无刷新,交互性更强的网页,那您的目标一定是Ajax. 介绍 在具体讨论Aj ...
- epic游戏平台如何启用认证器应用程序/二次验证码/谷歌身份验证器?
1.登陆epic游戏平台,找到二次验证绑定界面 登陆https://www.epicgames.com/store/zh-CN/, 点右上角用户头像-[账户]. 之后点-[密码与安全] 在[双重验证] ...
随机推荐
- 如何做系列(2)- XML转义字符
< < 小于号 > > 大于号 & & 和 ' ' 单引号 " " 双引号 也可以使用<![CDATA[ ]]> ...
- 二分判定 覆盖问题 BZOJ 1052
//二分判定 覆盖问题 BZOJ 1052 // 首先确定一个最小矩阵包围所有点,则最优正方形的一个角一定与矩形一个角重合. // 然后枚举每个角,再解决子问题 #include <bits/s ...
- 01.Hibernate快速入门
第一步:下载Hibernate5的运行环境 https://sourceforge.net/projects/hibernate/files/hibernate-orm/ 第二步:在数据库创建表 Cr ...
- 伸缩布局flex
一.伸缩布局的起源 1.之前我们想要适应不同的浏览器,一般采用的是设置宽度.高度为父级元素的百分比,但是有时候百分比的计算是相当复杂的,加上有时候还有规定的宽度要设置,所以,伸缩布局的出现是我们所急需 ...
- mysql大数据表优化
1.应尽量避免在 where 子句中使用!=或<>操作符,否则将引擎放弃使用索引而进行全表扫描. 2.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉 ...
- DVWA 之low级别sql注入
将Security level设为low,在左侧列表中选择“SQL Injection”,然后在右侧的“User ID”文本框中输入不同的数字就会显示相应的用户信息. 我们首先需要判断这里所传输的参数 ...
- Python学习之--数字转人民币读法(解决问题的方法很重要)
效果图: 实现代码: money = float(input("Please input the money:"))cop = int(money)Num = ['零','壹',' ...
- 两天了。照着SVN的界面画的一个界面。
可以选择显示哪些列. 界面上的东西,都简单,麻烦的是它的下层.下层全部用svn server的服务器自带的svn.exe来支持. 有些位置要启动svn.exe不止一次.所以参数的来回传递,来回组合 ...
- VS中warning MSB8004和error MSB4018解决方案
问题如下: warning MSB8004: Output Directory does not end with a trailing slash. This build instance wil ...
- StopWatch 监控Java代码运行时间和分析性能
背景 有时我们在做开发的时候需要记录每个任务执行时间,或者记录一段代码执行时间,最简单的方法就是打印当前时间与执行完时间的差值,然后这样如果执行大量测试的话就很麻烦,并且不直观,如果想对执行的时间做进 ...