JSP中圖片驗(yàn)證的完成
發(fā)表時間:2024-06-10 來源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要][前言]:圖片驗(yàn)證在有關(guān)注冊和發(fā)表留言經(jīng)常用到.我在此用jsp寫了個.供大家參考. 其中 com.sun.image 不是java的標(biāo)準(zhǔn)包.需要另外下載.相關(guān)地址為: http://java.sun.com/products/java-media/jai/ 1. random.jsp (產(chǎn)生...
[前言]:圖片驗(yàn)證在有關(guān)注冊和發(fā)表留言經(jīng)常用到.我在此用jsp寫了個.供大家參考. 其中
com.sun.image 不是java的標(biāo)準(zhǔn)包.需要另外下載.相關(guān)地址為:
http://java.sun.com/products/java-media/jai/
1. random.jsp (產(chǎn)生四位的隨機(jī)字符,由0-9,a-z,A-Z構(gòu)成.并把最終字符串放到session中保存以讓后續(xù)頁面驗(yàn)證真?zhèn)?
代碼如下:
<%@ 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);
//設(shè)置字體顏色
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();
%>
[page_break]
2. img.jsp (顯示驗(yàn)證圖片.由于本程序簡單讓驗(yàn)證程序也一并放在了一起)
代碼如下:
<%@ 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('驗(yàn)證碼錯誤!請重試。')</script>");
out.println("<script>history.go(-1)</script>");
//response.sendRedirect("img.jsp");
}
else
{
out.println("<center>驗(yàn)證成功!</center>");
}
}
%>
<html>
<head>
<title>圖片驗(yàn)證</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>
說明
:有興趣的網(wǎng)友可以在此基礎(chǔ)上增加圖片的內(nèi)容.比如讓背景加上紋理.讓字符位置歪斜以加大掃描程序的難度.大家有什么看法和建議,都可以回復(fù)中提出來
....