论坛首页 编程语言技术论坛

java实现网站登录验证码功能

浏览 2233 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (1)
作者 正文
   发表时间:2012-10-17  
验证码:
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int width=800;
int height=200;

//BufferedImage(画板)
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

//Graphics(画笔)
Graphics p=image.getGraphics();

p.setColor(getRandomColor());
//使用画笔填充一个矩形区域
p.fillRect(0, 0, width, height);

//画线
p.setColor(getRandomColor());
p.drawLine(0, height/2,width/2 ,0 );
p.drawLine(0, height/2, width/2, height);
p.drawLine(width/2, 0, width, height/2);
p.drawLine(width/2, height, width,height/2 );

//画图
p.setColor(getRandomColor());
int x=(int) (Math.random()*(width-height));
int y=0;
p.fillOval(x, y, height, height);

//随机的在画板上画100个园
for (int i = 0; i < 100; i++) {
p.setColor(getRandomColor());
int rx=(int) (Math.random()*width);
int ry=(int) (Math.random()*height);
p.fillOval(rx, ry, 2, 2);
}
//随机画100条干扰线
for (int i = 0; i < 10; i++) {
p.setColor(getRandomColor());
int x1=(int) (Math.random()*width);
int y1=(int) (Math.random()*height);
int x2=(int) (Math.random()*width);
int y2=(int) (Math.random()*height);
p.drawLine(x1, y1, x2, y2);
}

//画4个随机字符
int w=(width-5*6)/4;
String code="";
p.setFont(new Font("Arial",Font.HANGING_BASELINE, 55));
for (int i = 0; i < 4; i++) {
String s=getWord();
code=code+s;
p.setColor(getRandomColor());
p.drawString(s, 6+i*(w+6), 50);
}
System.out.println("Fuck!!!!"+code);
request.getSession().setAttribute("code", code);
//ImageIO(快递)
ImageIO.write(image, "png", response.getOutputStream());

}
private Color getRandomColor(){
int r=(int) (Math.random()*256);
int g=(int) (Math.random()*256);
int b=(int) (Math.random()*256);
return new Color(r,g,b);
}

public String getWord(){
int i=0;
while(!(i>=48&&i<=57||i>=65&&i<=90||i>=97&&i<=122)){
i=(int) (Math.random()*128);
}
char c=(char) i;
return c+"";
}
jsp页面img直接src指向这个servlet。。。。
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics