欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JSP動態(tài)生成驗(yàn)證碼存儲在session作用范圍內(nèi)

 更新時(shí)間:2014年09月10日 17:31:45   投稿:whsnow  
下面的代碼實(shí)現(xiàn)的功能:寫一個(gè)JSP頁,動態(tài)生成一個(gè)驗(yàn)證碼,存儲在session作用范圍內(nèi),并以圖像形式返回給客戶端顯示

(1)在登錄應(yīng)用中,為防止惡意登錄,常常需要服務(wù)器動態(tài)生成驗(yàn)證碼并存儲在session作用范圍中,最后以圖像形式返回給客戶端顯示

(2)下邊的代碼實(shí)現(xiàn)的功能:寫一個(gè)JSP頁,動態(tài)生成一個(gè)驗(yàn)證碼,存儲在session作用范圍內(nèi),并以圖像形式返回給客戶端顯示。

另寫一個(gè)JSP頁面,引用此JSP頁面生成的驗(yàn)證碼;

authen.jsp代碼如下:

<%@ page import="java.awt.*,java.awt.image.*,java.util.*,com.sun.image.codec.jpeg.*" %> 
<%! 
//根據(jù)提供的ab產(chǎn)生隨機(jī)的顏色變化范圍 
Color getColor(int a,int b){ 
int n=b-a; 
Random rd=new Random(); 
int cr=a+rd.nextInt(n); 
int cg=a+rd.nextInt(n); 
int cb=a+rd.nextInt(n); 

return new Color(cr,cg,cb); 
} 
%> 
<% //下邊三行取消客戶端游覽器緩存驗(yàn)證碼的功能 
response.setHeader("Pragma","No-cache"); 
response.setHeader("Cache-Control","no-cache"); 
response.setDateHeader("Expires", 0); 

int width=60, height=20; 
//在內(nèi)存中生成一個(gè)圖像 
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 

Graphics g = image.getGraphics(); 

Random random = new Random(); 

g.setColor(getColor(200,250)); 
g.fillRect(0, 0, width, height); 

g.setFont(new Font("Times New Roman",Font.BOLD,18)); 

g.setColor(getColor(160,200)); 
for (int i=0;i<160;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); 
} 

String number=String.valueOf(1000+random.nextInt(8999)); 
String name=request.getParameter("name"); 
session.setAttribute(name,number); 

g.setColor(getColor(20,130)); 
int x=(int)(width*0.2); 
int y=(int)(height*0.8); 
g.drawString(number,x,y); 
g.dispose(); 

JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(response.getOutputStream()); 
encoder.encode(image); 
out.close(); 
%>

再建一個(gè)test.jsp頁面 調(diào)用驗(yàn)證碼:

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 
<title>無標(biāo)題文檔</title> 
</head> 

<body> 
<% //同樣實(shí)現(xiàn)取消客戶端緩存 
response.setHeader("Pragma","No-cache"); 
response.setHeader("Cache-Control","no-cache"); 
response.setDateHeader("Expires", 0); 
String name="loginCode"; 
%> 
驗(yàn)證碼:<img src="authen.jsp?name=<%=name%>" /> 
</body> 
</html>

(3)在上述的兩個(gè)頁面中都有取消客戶端緩存的功能,這是因?yàn)樵儆械挠斡[器中,比如使用的IE游覽器的游覽方式,

會先將圖片放在緩存中,當(dāng)再次請求的時(shí)候會現(xiàn)在內(nèi)存中查找是不是已經(jīng)有了,有的話就不在請求,這使得在刷新驗(yàn)

證碼的時(shí)候 失敗,所以要使游覽器不讀取緩存的圖片,就需要取消緩存;

(4)OK!到此結(jié)束!

相關(guān)文章

最新評論