您的位置:首页 > Web前端 > JQuery

jsp+jquery 实现图片验证码(在主页面不刷新的情况下可更换图片)

2010-04-01 16:22 621 查看
原理如下:

1.写一个类生成图片文件(Image.java)

2.写一个jsp文件,用于生成图片(createimage.jsp)

3.写一个主页面,用于显示图片验证码(image.jsp)

4.写一个jsp文件,动态加载图片,用于更换图片验证码(imagesrc.jsp)

5.写一个验证图片验证码是否正确的jsp文件

 

在image.jsp中获取createimage.jsp中生成的图片,然后显示出来,点击更换图片的时候,自动在显示图片的<td>中加载imagesrc.jsp页面的内容

(该页面只包含一个图片),因为浏览器不会重复访问同一URL的资源,所以每次访问createimage.jsp时在后面追加一个时间戳,于是在image.jsp中不用刷新整个页面便可更换图片验证码了,每次获取验证码时,将验证码图片中包含的字符串值存入session中,在用户填写获取的验证码后提交时,通过JavaScript将用户填写的内容与session中的值比较,正确则提交成功,否则提交失败!

 

代码如下:

 

1、生成图片的Java类:Image.java

 

package test.image;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
public class Image {
HttpServletResponse response ;
// 验证码图片中可以出现的字符集,可根据需要修改
private char mapTable[] = { 'a', 'b', 'c', 'd', 'e', 'h', 'j', 'k', 'm',
'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0','1',
'2', '3', '4', '5', '6', '7', '8', '9','A','B','C','D','E','F','G',
'H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

public Image(HttpServletResponse response){
this.response = response ;
}
public String getCertPic(int width, int height) {
if (width <= 0) {
width = 60;
}
if (height <= 0) {
height = 20;
}
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
// 设定背景颜色
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, width, height);
// 画边框
g.setColor(Color.black);
g.drawRect(0, 0, width - 1, height - 1);
// 随机产生的验证码
String strEnsure = "";
// 4代表4位验证码,如果要生成等多位的验证码 ,则加大数值
for (int i = 0; i < 4; i++) {
strEnsure += mapTable[(int) (mapTable.length * Math.random())];
}
// 将验证码显示在图像中,如果要生成更多位的验证码,增加drawString语句
g.setColor(Color.red);
g.setFont(new Font("Atlantic Inline", Font.PLAIN, 18));
String str = strEnsure.substring(0, 1);
g.drawString(str, 8, 17);
str = strEnsure.substring(1, 2);
g.drawString(str, 20, 15);
str = strEnsure.substring(2, 3);
g.drawString(str, 35, 18);
str = strEnsure.substring(3, 4);
g.drawString(str, 45, 15);
// 随机产生10个干扰点
Random random = new Random();
for (int i = 0; i < 10; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
g.drawOval(x, y, 1, 1);
} // 释放图形上下文
g.dispose();
try { // 输出图像到页面
ImageIO.write(image, "JPEG", response.getOutputStream());
} catch (IOException e) {
return "";
}finally{
try {
response.getOutputStream().flush();
response.getOutputStream().close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
return strEnsure;
}
}


 

2、生成图片的jsp文件 :createimage.jsp

 

<%@ page contentType="image/jpeg" import="test.image.*"%>
<%
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
Image image = new Image(response);
String rs = image.getCertPic(60,20);
session.setAttribute("imageString",rs);

%>


 

 

3、显示图片验证码的页面:image.jsp

 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<%
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache,must-revalidate");
response.setHeader("Expires","0");

%>

<title>pictrue</title>

<!--
<link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">
-->
<mce:script type="text/javascript" src="../jslib/jquery-1.4.js" mce_src="jslib/jquery-1.4.js"></mce:script>
<mce:script type="text/javascript" src="../jslib/imagecheck.js" mce_src="jslib/imagecheck.js"></mce:script>
</head>

<body>
<center>
<div id="tableDiv">

<table name="table" id="tab" border="0">
<tr>
<td id="tdNode">
<input type="text" id="inputNode" name="image" maxlength="10"/>
</td>
<td id="imageNode">
<img src="createimage.jsp?asktime='<%=new Date() %>'" mce_src="createimage.jsp" />
</td>
<td>
<font size="2"><a href="#" mce_href="#" onclick="changeImage()">看不清楚,换一张</a></font>
</td>
</tr>
<tr>
<td colspan="3"><input type="button" value="validate" class="button" onclick="validate()"/></td>
<td><input type="hidden" name="valid" id="val" value="0"/></td>
</tr>

</table>
</div>
</center>
</body>
</html>


 

4、用于加载动态图片的页面:imagesrc.jsp

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<mce:script type="text/javascript" src="../jslib/jquery-1.4.js" mce_src="jslib/jquery-1.4.js"></mce:script>

</head>
<body>
<img name="image" src="createimage.jsp?asktime='<%=new Date() %>'"/>

</body>
</html>


 

5、获取图片验证码中字符串内容的jsp文件:

 

<%@ page language="java" pageEncoding="utf-8"%>
<%
out.print((String)session.getAttribute("imageString"));
%>


 

image.jsp
4000
的JavaScript代码:

 

function changeImage(){
$("table").find("#imageNode").load("imagesrc.jsp");
}
function validate(){

var text = $("table").find("#inputNode").attr("value");
$.ajax({
type:"POST",
url:"getsession.jsp",
success:function(msg){
msg = jQuery.trim(msg);
if(msg==text){
alert("success");
}else{
alert("fail");
$("table").find("#inputNode").focus();
}
}
});
}


 

写完这些必要的文件后,便可以在浏览器上验证了.

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息