本文实例讲述了jsp实现简单验证码的方法。分享给大家供大家参考。具体如下:
这里只有一个文件,可以在<img />的src属性里直接调用显示,适用于各种项目的表单安全验证
jsp页面代码:
<%@ page contenttype="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
<%!
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 image = new bufferedimage(width, height, bufferedimage.type_int_rgb);
graphics g = image.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(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);
}
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.setattribute("rand",srand);
g.dispose();
imageio.write(image, "jpeg", response.getoutputstream());
response.getoutputstream().flush();
response.getoutputstream().close();
out.clear();
out=pagecontext.pushbody();
%>
希望本文所述对大家的jsp程序设计有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!