java实现空心验证码_java实现验证码功能

packagecom.verification_code.servlet;importjava.awt.Color;importjava.awt.Font;importjava.awt.Graphics;importjava.awt.image.BufferedImage;importjava.io.IOException;importjava.io.OutputStream;importjava.util.Random;importjavax.imageio.ImageIO;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;public class ImgServlet extendsHttpServlet{

@Overrideprotected voiddoGet(HttpServletRequest req, HttpServletResponse resp)throwsServletException, IOException {//TODO Auto-generated method stub

doPost(req,resp);

}

@Overrideprotected voiddoPost(HttpServletRequest req, HttpServletResponse resp)throwsServletException, IOException {//TODO Auto-generated method stub//设置响应开头

resp.setContentType("image/jpeg");//设置页面不缓存

resp.setHeader("pragma", "no-cache");

resp.setHeader("cache-control", "no-cache");

resp.setDateHeader("expires", 0);

OutputStream out=resp.getOutputStream();//设置图片的宽高

int width=88,height=20;

BufferedImage image= newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

Graphics g=image.getGraphics();//生成随机类

Random random = newRandom();

g.setColor(Color.WHITE);

g.fillRect(0, 0, width, height);//设置字体

g.setFont(new Font("Times New Roman",Font.BOLD+Font.ITALIC,18));//画边框

g.setColor(getRandColor(0, 20)); //---2

g.drawRect(0, 0, width - 1, height - 1);//随机产生干扰线

int count = 100;int lineWidth = 3; //干扰线的宽度

for (int i = 0; i < count; i++) {

g.setColor(getRandColor(150, 200)); //---3

int x = random.nextInt(width - lineWidth - 1) + 1; //保证画在边框之内

int y = random.nextInt(height - lineWidth - 1) + 1;int xl =random.nextInt(lineWidth);int yl =random.nextInt(lineWidth);

g.drawLine(x, y, x+ xl, y +yl);

}//生成随机验证码

String sRand="";

String str[]={"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};for(int i=0;i<4;i++){int rand = random.nextInt(36);

sRand+=str[rand];//设置随机颜色

g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));//绘制

g.drawString(str[rand], 20*i+8, 16);

}

req.getSession().setAttribute("Verification_code",sRand);

g.dispose();

ImageIO.write(image,"JPEG", out);

}public Color getRandColor(int fc, int bc) { //取得给定范围随机颜色

Random random = newRandom();if (fc > 255) {

fc= 255;

}if (bc > 255) {

bc= 255;

}int r = fc + random.nextInt(bc -fc);int g = fc + random.nextInt(bc -fc);int b = fc + random.nextInt(bc -fc);return newColor(r, g, b);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值