【Java】使用Servlet生成随机验证码图片

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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值