您的位置:首页 > 编程语言 > Java开发

struts1 登陆验证码实现

2013-03-21 09:10 344 查看
      这两天在由于项目需要做了个验证码登陆,在网上找了找,思路大志是在后台生成验证码图片,以图片流的形式传到前台,仅供参考~~

 

后台生成验证码图片:

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);
OutputStream os=response.getOutputStream();
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200,250));
g.fillRect(0, 0, width, height);
g.setColor(new Color(255, 255, 255));
for (int i=0;i<155;i++)
{
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(40);
int yl = random.nextInt(40);
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(0, 0, 0));
g.drawString(rand,14 * i,18);
}
//赋值验证码
CHECK_IMAGE = sRand;
g.dispose();
ImageIO.write(image, "jpeg",os);
request.setAttribute("image", image);
response.flushBuffer();
os.flush();
os.close();
os=null;
return null;
}catch(IllegalStateException e){
System.out.println(e.getMessage());
e.printStackTrace();
}


 

前台使用html img标签接收图片~~

<img src="index.do?command=toLoginpicture" id="Verify"  name="Verify" style="cursor:hand;" alt="看不清,换一张" onclick="changePic()"/><span style="color:red">${checkimage}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: