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

验证码:
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。。。。

猜你喜欢

转载自963661329.iteye.com/blog/1699977
今日推荐