生成验证码工具类:ValidateCode.java
package com.singlee.util; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Random; import javax.imageio.ImageIO; /** * 验证码生成器 * */ public class ValidateCode { // 图片的宽度。 private int width = 80; // 图片的高度。 private int height = 35; // 验证码字符个数 private int codeCount = 4; // 验证码干扰线数 private int lineCount = 100; // 验证码 private String code = null; // 验证码图片Buffer private BufferedImage buffImg = null; private char[] codeSequence = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" .toCharArray(); public ValidateCode() { this.createCode(); } /** * * @param width * 图片宽 * @param height * 图片高 */ public ValidateCode(int width, int height) { this.width = width; this.height = height; this.createCode(); } /** * * @param width * 图片宽 * @param height * 图片高 * @param codeCount * 字符个数 * @param lineCount * 干扰线条数 */ public ValidateCode(int width, int height, int codeCount, int lineCount) { this.width = width; this.height = height; this.codeCount = codeCount; this.lineCount = lineCount; this.createCode(); } public void createCode() { int fontwidth = width / (codeCount+2);// 每个字符的宽度 int fontHeight = height - 4;// 字体的高度 int codeY = height - 8; // 图像buffer buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = buffImg.createGraphics(); // 将图像填充为白色 g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); // 创建字体 Font font = new Font("Arial", Font.PLAIN, fontHeight); g.setFont(font); // 生成随机数 Random random = new Random(); // 绘制干扰线 for (int i = 0; i < lineCount; i++) { int xs = random.nextInt(width); int ys = random.nextInt(height); int xe = xs + random.nextInt(width / 8); int ye = ys + random.nextInt(height / 8); // 随机颜色 g.setColor(getRandomColor()); g.drawLine(xs, ys, xe, ye); } // randomCode记录随机产生的验证码 StringBuffer randomCode = new StringBuffer(); // 随机产生codeCount个字符的验证码。 for (int i = 0; i < codeCount; i++) { String strRand = String.valueOf(codeSequence[random .nextInt(codeSequence.length)]); // 产生随机的颜色值,让输出的每个字符的颜色值都将不同。 g.setColor(getRandomColor()); g.drawString(strRand, (i + 1) * fontwidth, codeY); // 将产生的四个随机数组合在一起。 randomCode.append(strRand); } // 将四位数字的验证码保存到Session中。 code = randomCode.toString(); } /** * 获取一个随机的颜色 * * @return */ private Color getRandomColor() { Random random = new Random(); int r = random.nextInt(255); int g = random.nextInt(255); int b = random.nextInt(255); Color c = new Color(r, g, b); return c; } public void write(String path) throws IOException { OutputStream os = new FileOutputStream(path); this.write(os); } public void write(OutputStream os) throws IOException { ImageIO.write(buffImg, "png", os); os.close(); } /** * 获取图片BufferedImage * * @return */ public BufferedImage getBuffImg() { return buffImg; } /** * 获取验证码字符串 * * @return */ public String getCode() { return code; } }
处理验证码请求的控制层:ValidateCodeController.java
package com.singlee.controller; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.singlee.controller.common.BaseController; import com.singlee.model.common.ComException; import com.singlee.util.ValidateCode; /** * 验证码 * * @author Ming * */ @Controller @RequestMapping("/validatecode") public class ValidateCodeController extends BaseController { @RequestMapping("randomcode") public void randomCode(HttpServletRequest req, HttpServletResponse resp) throws ComException { // 设置响应的类型格式为图片格式 resp.setContentType("image/jpeg"); // 禁止图像缓存。 resp.setHeader("Pragma", "no-cache"); resp.setHeader("Cache-Control", "no-cache"); resp.setDateHeader("Expires", 0); HttpSession session = req.getSession(); ValidateCode vCode = new ValidateCode(80, 35, 4, 70); System.out.println("code:" + vCode.getCode()); //验证码保存到Session session.setAttribute("code", vCode.getCode()); try { vCode.write(resp.getOutputStream()); } catch (IOException e) { e.printStackTrace(); throw new ComException("输出验证码图片异常:"+e.getMessage()); } } }
页面显示:login.jsp
<div id="checkCodePanel" class="row"> <label id="f_checkCode" class="field" style="visibility: visible;color: #999"> 请输入右侧验证码 </label> <img class="checkImg" id='checkImg' src="<%=basePath%>validatecode/randomcode" /> <input name="checkCode" class="text_checkcode" type="text" id="checkCode" size="6" /> </div>
点击刷新验证码:login.js
// 单击验证码刷新 $('#checkImg').click(function() { $('#checkImg').attr('src', 'validatecode/randomcode?d=' + Math.random()); });