本文实例为大家分享了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个数字的时候就会出现提示
运行结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:- asp.net ajax实现无刷新验证码
- 基于Ajax用户名验证、服务条款加载、验证码生成的实现方法
- Ajax实现带有验证码的局部刷新登录界面
- Ajax和PHP正则表达式验证表单及验证码
- PHP+Ajax验证码验证用户登录
- thinkphp验证码的实现(form、ajax实现验证)
- jsp+ajax实现的局部刷新较验验证码(onblur事件触发较验)
- PHP生成各种常见验证码和Ajax验证过程
- Ajax提交表单时验证码自动验证 php后端验证码检测
- PHP+Ajax实现验证码的实时验证