JSP做無刷新的驗證碼:
一共兩個頁面:
第一個image.jsp
一下是Image.jsp源代碼
[java]
<%@ page language="java" import="java.util.*,java.awt.image.*,java.awt.*,javax.imageio.*" pageEncoding="GBK" contentType="image/jpeg"%>
<!-- 記得contentType="image/jpeg" -->
<%!
Color getRandColor(int start,int end,long seed)
{
if(start>255)
{
start=255;
}
Random random=new Random(seed);
int r=start+random.nextInt(end+1-start);
int g=start+random.nextInt(end+1-start);
int b=start+random.nextInt(end+1-start);
return new Color(r,g,b);
}
%>
<%
int width=60;
int height=20;
//隨機產生的驗證碼中的字母,可以設置多一點
String[] str={"1","a","A","B","c","2","I","8","U","y"};
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//這就算是有紙了,需要知道寬度高度
Graphics g=image.getGraphics();
//這就算有筆了
g.setColor(getRandColor(230,250,System.currentTimeMillis()));
//這就算把筆蘸上顏色了
g.fillRect(0,0,width,height);
//填充底色
Random random=new Random(System.currentTimeMillis());
//畫干擾線
g.setColor(getRandColor(160,200,System.currentTimeMillis()));
for(int i=0;i<50;i++)
{
g.drawLine(random.nextInt(6),random.nextInt(15),
random.nextInt(6)+random.nextInt(56),random.nextInt(7)+random.nextInt(17));
}
String check=new String();
g.setFont(new Font("Times new Roman",Font.PLAIN,18));
for(int i=0;i<4;i++)
{
g.setColor(getRandColor(20,110,System.currentTimeMillis()+i*1000));
//String ran=String.valueOf(random.nextInt(10));
int temp=random.nextInt(10);
String ran=str[temp];
check+=ran;
g.drawString(ran,6+i*13,16);//分別往上寫數字
}
//可以通過session來獲取隨機產生的驗證碼
session.setAttribute("check",check);
g.dispose();
//使圖像生效
//response.setCharacterEncoding("GBK");
//request.setCharacterEncoding("GBK");
ImageIO.write(image,"JPEG",response.getOutputStream());
//將圖像輸出,三個參數分別為紙,格式,服務器相應的輸出流
out.clear();
out=pageContext.pushBody();
//加上這兩句,tomcat就沒有異常信息
%>
然後在其他地方使用。
[html]
<body>
<img src="image.jsp" id="code"/> <a href="#" onclick="reload()">刷新</a>
<script>
function reload(){
document.getElementById("code").setAttribute("src","image.jsp?a="+new Date().getTime());
}
</script>
</body>