java 生成验证码

项目中看到验证码的生成不是直接用的图片,而是根据自己的properties属性文件用java开发的。
我在这里做一个记录:
一个很简单的应用,就是一个jsp页面来展示一个生成的验证码的图片。
首先来看一下效果:

[img]http://dl2.iteye.com/upload/attachment/0096/5126/f40d8b75-2b55-3bda-9e63-df3ded5819ac.png[/img]

这个验证码的长度可以根据自己的需要设置成指定的长度。当然,那样的话,图片长高也要相应的做修改。

1.开发环境:IDE:MyEclipse 10 + jdk1.6.0_43 + tomcat-7.0.53
2.新建一个动态的web project。
3.主要涉及到了这么几个文件:
验证码属性配置文件:imgCode.properties
获取配置文件通用类:Config.java
登录验证码配置:RandomConf.java
以及生成验证码的servlet类:VerifyCodeServlet.java

4.主要servlet处理类源码:VerifyCodeServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
System.setProperty("java.awt.headless", "true");
BufferedImage buffImg = new BufferedImage(RandomConf.getWidth(), RandomConf.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
// g.setColor(Color.WHITE);
g.setColor(new Color(
RandomConf.getRed(),
RandomConf.getGreen(),
RandomConf.getBlue()));
g.fillRect(0, 0, RandomConf.getWidth()-2, RandomConf.getHeight()-2);

Font font = new Font(RandomConf.getFontType(), Font.PLAIN, RandomConf.getFontSize());
g.setFont(font);
g.setColor(Color.BLACK);
g.drawRect(0, 0, RandomConf.getWidth() - 2, RandomConf.getHeight() - 2);

g.setColor(Color.GRAY);

Random random = new Random();

for (int i = 0; i < RandomConf.getComplex(); i++) {
int x1 = random.nextInt(RandomConf.getWidth()-2);
int y1 = random.nextInt(RandomConf.getHeight()-2);

int x2 = random.nextInt(10);
int y2 = random.nextInt(10);

g.drawLine(x1, y1, x1 + x2, y1 + y2);//在点(x1, y1)与点(x1 + x2, y1 + y2)之间画一条线
}

StringBuffer randomCode = new StringBuffer();
int red = 0;
int green = 0;
int blue = 0;
// 设置备选验证码:包括"A-Z","a-z","0-9"
int size = RandomConf.getRandomChar().length();
Random rand = new Random();
for (int i = 0; i < RandomConf.getLen(); i++) {
int start = rand.nextInt(size);
String tmpStr = RandomConf.getRandomChar().substring(start, start + 1);

red = random.nextInt(110);
green = random.nextInt(50);
blue = random.nextInt(255);
g.setColor(new Color(red,green,blue));

randomCode.append(tmpStr);
g.drawString(tmpStr, 13 * i + 6 + rand.nextInt(5), 14 + rand.nextInt(6));
}

HttpSession session = request.getSession();
session.setAttribute("randomImgCode", randomCode.toString());

response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");

ServletOutputStream outputStream = response.getOutputStream();
ImageIO.write(buffImg, "jpeg", outputStream);

outputStream.close();
}


后面附上整个项目代码,直接解压,导入myeclipse即可运行
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值