在登录应用中,为防止恶意登录,常常需要服务器动态生成验证码并存储在session作用范围中,最后以图像形式返回给客户端显示
下边的代码实现的功能:写一个jsp页,动态生成一个验证码,存储在session作用范围内,并以图像形式返回给客户端显示。
另写一个jsp页面,引用此jsp页面生成的验证码;
authen.jsp代码如下:
<%@ page import="java.awt.*,java.awt.image.*,java.util.*,com.sun.image.codec.jpeg.*" %>
<%!
//根据提供的ab产生随机的颜色变化范围
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);
}
%>
<% //下边三行取消客户端游览器缓存验证码的功能
response.setheader("pragma","no-cache");
response.setheader("cache-control","no-cache");
response.setdateheader("expires", 0);
int width=60, height=20;
//在内存中生成一个图像
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();
%>
再建一个test.jsp页面 调用验证码:
<%@ 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>无标题文档</title>
</head>
<body>
<% //同样实现取消客户端缓存
response.setheader("pragma","no-cache");
response.setheader("cache-control","no-cache");
response.setdateheader("expires", 0);
string name="logincode";
%>
验证码:<img src="authen.jsp?name=<%=name%>" />
</body>
</html>
在上述的两个页面中都有取消客户端缓存的功能,这是因为再有的游览器中,比如使用的ie游览器的游览方式,会先将图片放在缓存中,当再次请求的时候会现在内存中查找是不是已经有了,有的话就不在请求,这使得在刷新验证码的时候 失败,所以要使游览器不读取缓存的图片,就需要取消缓存。
以上就是本文的全部内容,希望对大家的学习有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!