(1)在登录应用中,为防止恶意登录,常常需要服务器动态生成验证码并存储在session作用范围中,最后以图像形式返回给客户端显示
(2)下边的代码实现的功能:写一个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>
(3)在上述的两个页面中都有取消客户端缓存的功能,这是因为再有的游览器中,比如使用的IE游览器的游览方式,
会先将图片放在缓存中,当再次请求的时候会现在内存中查找是不是已经有了,有的话就不在请求,这使得在刷新验
证码的时候 失败,所以要使游览器不读取缓存的图片,就需要取消缓存;
(4)OK!到此结束!
本文地址:https://www.stayed.cn/item/10355
转载请注明出处。
本站部分内容来源于网络,如侵犯到您的权益,请 联系我