驗證碼圖片是防止惡性註冊和登陸的有效手段,今天對系統加了個驗證碼圖片驗證,感受效果很好,如今把代碼和流程寫下:
1.保存驗證碼圖片生成源代碼爲p_w_picpath.jsp,以下:
<%@ page language="java" import="java.awt.*,java.awt.p_w_picpath.*,java.util.*,javax.p_w_picpathio.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<head>
<title>My JSP 'p_w_picpath.jsp' starting page </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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<%!
Color getRandColor(int fc,int bc){//給定範圍得到隨機顏色
Random random = new Random();
if(fc>255) fc=255;
if(bc>255) bc=255;
int r=fc+random.nextInt(bc-fc);
int g=fc+random.nextInt(bc-fc);
int b=fc+random.nextInt(bc-fc);
return new Color(r,g,b);
}
%>
<%
//設置頁面不緩存
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
// 在內存中建立圖象
int width=60, height=20;
BufferedImage p_w_picpath = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 獲取圖形上下文
Graphics g = p_w_picpath.getGraphics();
//生成隨機類
Random random = new Random();
// 設定背景色
g.setColor(getRandColor(200,250));
g.fillRect(0, 0, width, height);
//設定字體
g.setFont(new Font("Times New Roman",Font.PLAIN,18));
//畫邊框
//g.setColor(new Color());
//g.drawRect(0,0,width-1,height-1);
// 隨機產生155條幹擾線,使圖象中的認證碼不易被其它程序探測到
g.setColor(getRandColor(160,200));
for (int i=0;i <155;i++)
{
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x,y,x+xl,y+yl);
}
// 取隨機產生的認證碼(4位數字)
String sRand="";
for (int i=0;i <4;i++){
String rand=String.valueOf(random.nextInt(10));
sRand+=rand;
// 將認證碼顯示到圖象中
g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));//調用函數出來的顏色相同,多是由於種子太接近,因此只能直接生成
g.drawString(rand,13*i+6,16);
}
// 將認證碼存入SESSION
session.setAttribute("checkcode",sRand);
// 圖象生效
g.dispose();
// 輸出圖象到頁面
ImageIO.write(p_w_picpath, "JPEG", response.getOutputStream());
out.clear();
out = pageContext.pushBody();
%>
2.在須要驗證碼的頁面中增長以下內容:
//驗證碼javascript代碼
<script type="text/javascript">
function chk_p_w_picpath(){
var img = document.getElementById("pic");
img.src = "p_w_picpath.jsp?" + Math.random();
}
</script>
//增長驗證碼地方的代碼
<img id="pic" border=0
src="p_w_picpath.jsp?,Math.random();"
chk_p_w_picpath();" alt="刷新驗證碼">
3.Action中驗證碼驗證源代碼以下:
// 先判斷驗證碼是否正確
String ccode = (String) request.getSession().getAttribute("checkcode");
String checkcode = logonForm.getCheckcode();
if (!(checkcode.equals(ccode))) {
request.setAttribute("checkerror", "驗證碼輸入有誤!");
return mapping.findForward("logonfailure");
}
到此,驗證碼圖片驗證工做已經OK了,點擊驗證碼圖片還能夠刷新,怎麼樣,還不錯吧!不過這驗證碼圖片比較清晰了,通常是不須要刷新的。