1.定义一张图片,并且确定它的大小
int width=130,height=30;
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
2.定义画笔获取图片为画布
Graphics g = image.getGraphics();
3.画背景色
public void drawPic(){
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
}
4.设置随机画笔的颜色
public void setColor(){
Random r = new Random();
g.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
}
5.画随机干扰线
public void drawLine(){
setColor();
Random r = new Random();
for(int i=0;i<10;i++){
int xb = r.nextInt(width);
int yb = r.nextInt(height);
int xe = r.nextInt(width);
int ye = r.nextInt(height);
g.drawLine(xb, yb, xe, ye);
}
}
6.画5个随机字符(0~9,a~z,A~Z)
public void drawString(){
String words = "01234567890abcdefghijklm
nopqrstuvwxyzABCDEFGHIJK
LMNOPQRSTUVWXYZ";
g.setFont(new Font("Carlibri",Font.ITALIC,30));
for(int i=0;i<5;i++){
Random r = new Random();
char s = words.charAt(r.nextInt(62));
setColor();
g.drawString(String.valueOf(s), 25*i+5, 25);
}
}
7.把实际运行的函数组合起来,放在Servlet的doGet()中。
在要放置验证码图片的页面添加代码:<img src=”servlet的路径” onClick=”refreshCode()”>.
8.添加javascrpit代码
function refreshCode(){
location.href(“本页面地址”);
}
9.在servlet的doGet()设置不存储缓存
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Cache-Control", "no-cache");
resp.setDateHeader("Expires", 0);