Java实现验证码制作

来源:互联网 发布:淘宝差评店主报复 编辑:程序博客网 时间:2024/05/22 10:47

为什么要使用验证码


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


使用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);}// 存sessionHttpSession 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();}



0 0
原创粉丝点击