您的位置:首页 > 编程语言 > Java开发

Java实现验证码制作

2015-09-15 13:26 801 查看
为什么要使用验证码

通过验证码来区分用户是人还是计算机。防止恶意破解密码,刷票,防止黑客的恶意登陆操作。

使用Servlet实现验证码

<div class="form-group">
<input type="text" class="form-control login-field" value=""
<span style="white-space:pre">	</span>placeholder="请输入验证码" id="login-code" name="login-code" required="required" form="loginForm">
<label class="login-field-icon fui-eye" for="login-code"></label>
<a href="#"> <img id="validateImg1" src="/cocoala/securityCode?t=<%= new Date()%>" onclick="showValidateCode1();" title="点击更新验证码" class="code" />
<span title="刷新" onclick="showValidateCode1();"></span>
</a>
</div>


生成验证码需要的类

1)BufferedImage:图像数据缓冲区

2)Graphics2D:绘制图片

3)Color:获取颜色

4)Random:获取随机数

5)ImageIO:输出图片

实现生成图片Servlet的步骤

/**
* @param req
* @param resp
* @throws ServletException
* @throws java.io.IOException
*/
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, java.io.IOException {
// 1. 定义BufferedImage对象
BufferedImage buffImg = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 2. 获取Graphics对象
Graphics2D gd = buffImg.createGraphics();

gd.setColor(Color.WHITE); // 背景
gd.fillRect(0, 0, width, height); // 边框

Font font = new Font("宋体", Font.PLAIN, fontHeight);

gd.setFont(font);

gd.setColor(Color.BLACK);
gd.drawRect(0, 0, width - 1, height - 1);

StringBuffer randomCode = new StringBuffer();
int red = 0, green = 0, blue = 0;

// 随机生成验证码
Random random = new Random();
int allCodesCount = codeSequence.length;
for (int i = 0; i < codeCount; i++) {

String strRand = String.valueOf(codeSequence[random
.nextInt(allCodesCount)]);

red = random.nextInt(200);
green = random.nextInt(200);
blue = random.nextInt(200);

gd.setColor(new Color(red, green, blue));
gd.drawString(strRand, (i * xx) + xx / 2, codeY);

randomCode.append(strRand);
}

// 画干扰线
gd.setColor(new Color(red, green, blue));
for (int i = 0; i < 10; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(30);
int yl = random.nextInt(30);
gd.drawLine(x, y, x + xl, y + yl);
}

// 存session
HttpSession session = req.getSession();
session.setAttribute("validateCode", randomCode.toString());

resp.setHeader("Pragma", "no-cache");
resp.setHeader("Cache-Control", "no-cache");
resp.setDateHeader("Expires", 0);

resp.setContentType("image/jpeg");

ServletOutputStream sos = resp.getOutputStream();
ImageIO.write(buffImg, "jpeg", sos);
sos.close();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: