圖片驗證在有關注冊和發表留言經常用到.我在此用jsp寫了個.供大家參考. 其中 com.sun.image 不是java的標準包.需要另外下載.相關地址為:
http://java.sun.com/products/java-media/jai/
1. random.jsp (產生四位的隨機字符,由0-9,a-z,a-z構成.并把最終字符串放到session中保存以讓后續頁面驗證真偽)
代碼如下:
<%@ page autoflush="false" import="java.util.*,java.awt.*,java.awt.image.*,com.sun.image.codec.jpeg.*,java.util.*"%>
<%@ page import="" contenttype="text/html; charset=gb2312"%>
<%
string chose="0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
char display[]={'0',' ','0',' ','0',' ','0'},ran[]={'0','0','0','0'},temp;
random rand=new random();
for(int i=0;i<4;i++)
{
temp=chose.charat(rand.nextint(chose.length()));
display[i*2]=temp;
ran[i]=temp;
}
string random=string.valueof(display);
session.setattribute("random",string.valueof(ran));
%>
<%
out.clear();
response.setcontenttype("image/jpeg");
response.addheader("pragma","no-cache");
response.addheader("cache-control","no-cache");
response.adddateheader("expries",0);
int width=47, height=15;
bufferedimage image = new bufferedimage(width, height, bufferedimage.type_int_rgb);
graphics g = image.getgraphics();
//以下填充背景顏色
g.setcolor(color.green);
g.fillrect(0, 0, width, height);
//設置字體顏色
g.setcolor(color.red);
g.drawstring(random,3,10);
g.dispose();
servletoutputstream outstream = response.getoutputstream();
jpegimageencoder encoder =jpegcodec.createjpegencoder(outstream);
encoder.encode(image);
outstream.close();
%>
2. img.jsp (顯示驗證圖片.由于本程序簡單讓驗證程序也一并放在了一起)
代碼如下:
<%@ page contenttype="text/html; charset=gb2312" language="java"%>
<%
string num=request.getparameter("num");
string random=(string)session.getattribute("random");
if(num!=null&&random!=null)
{
if(!num.equals(random))
{
out.println("<script>alert('驗證碼錯誤!請重試。')</script>");
out.println("<script>history.go(-1)</script>");
//response.sendredirect("img.jsp");
}
else
{
out.println("<center>驗證成功!</center>");
}
}
%>
<html>
<head>
<title>圖片驗證</title>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
</head>
<body>
<form action="img.jsp" method="post">
<table>
<tr>
<td>
<input type="text" name="num" size=10>
</td>
<td>
<img src="random.jsp">
</td>
</tr>
</table>
<input type="submit" value="ok">
</form>
</body>
</html>
說明: 有興趣的網友可以在此基礎上增加圖片的內容.比如讓背景加上紋理.讓字符位置歪斜以加大掃描程序的難度. 大家有什么看法和建議,都可以回復中提出來....
新聞熱點
疑難解答