案例实现效果
用户在前端输入验证码,按键收起触发异步验证,验证验证码的对错
前端代码
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;}
}