您的位置:首页 > Web前端 > JavaScript

JSP中生成验证码

2007-10-26 14:39 260 查看
JSP中生成验证码

这是我根据别人代码完善的,现在可以运行
VerifyCode.java


package image;


import java.awt.Color;


import java.awt.Font;


import java.awt.Graphics;


import java.awt.image.BufferedImage;


import java.util.Random;






/** *//**


*


* @author Wencheng Ma


*


*/




public class VerifyCode ...{




public String s = "";






public VerifyCode()...{




}






/** *//**


* get a new color by ranges


* @param i


* @param j


* @return Color


*/




public Color getColor(int i, int j) ...{


Random random = new Random();






if (i > 255) ...{


i = 255;


}




if (j > 255) ...{


j = 255;


}




int r = i + random.nextInt(j - i);


int g = i + random.nextInt(j - i);


int b = i + random.nextInt(j - i);




return new Color(r, g, b);


}






/** *//**


* create a verify code of image


* @return


*/




public BufferedImage createVerifyCode() ...{




//在内存中创建图像


int width = 60;


int height = 20;


BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);




//获取图像上下文


Graphics graphics = bufferedImage.getGraphics();




//随机类


Random random = new Random();




//设置背景色


graphics.setColor(getColor(200, 250));


graphics.fillRect(0, 0, width, height);




//设置字体


graphics.setFont(new Font("Times New Roman", Font.PLAIN, 18));




//155条随机干扰点


graphics.setColor(getColor(160, 200));




for (int i = 0; i < 155; i++) ...{


int x1 = random.nextInt(width);


int y1 = random.nextInt(height);


int x2 = random.nextInt(12);


int y2 = random.nextInt(12);


graphics.drawOval(x1, y1, x1 + x2, y1 + y2);


// 干扰线


// graphics.drawLine(x1, y1, x1 + x2, y1 + y2);


}




//4位随机验证码




for (int i = 0; i < 4; i++) ...{


String rand = String.valueOf(random.nextInt(10));


s += rand;


graphics.setColor(new Color(20 + random.nextInt(100), 20 + random.nextInt(100), 20 + random.nextInt(100)));


graphics.drawString(rand, 13 * i + 6, 16);


}




//图像生效


graphics.dispose();




return bufferedImage;


}


}



JSP页面


<jsp:directive.page import="image.VerifyCode" />


<jsp:directive.page import="javax.imageio.ImageIO"/>


<jsp:useBean id="image" scope="session" class="image.VerifyCode"/>




<%


//设置页面不缓存


response.setHeader("Pragma", "No-cache");


response.setHeader("Cache-Control", "no-cache");


response.setDateHeader("Expires", 0);




// 将认证码存入SESSION


session.setAttribute("rand", image.s);




// 输出图象到页面


ImageIO.write(image.createVerifyCode(), "JPEG", response.getOutputStream());


%>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: