关于校验码的文章网上非常多,很多人采用开源JCaptcha作为验证码框架,JCaptcha有很多优点,但配置还是复杂,而且生成的图片对于企业级应用来说辨识度低了点,而这有可能会导致客户投诉,本篇采用简单的方式生成辨识度高的验证码,基本满足内部网企业级应用(有些企业的老头老太太基本不能正确输入辨识度低的验证码,大量投诉会搞死开发人员的):
1、建立校验码服务类,其中图片宽高以及校验码长度可以配置,请仔细测试生成的图片来满足应用需求,提供了两种类型的校验码,一种是数字校验码,一种是字母数字混合校验码,根据企业需要任选一种:
@Service public class CheckCodeService { // 校验码图片宽 private int width = 85; // 校验码图片高 private int height = 20; // 校验码长度 private int codeLength = 6; // 混合字母数字数组 private String[] charArray = new String[]{"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","W","Z"}; public void setCodeLength(int codeLength) { this.codeLength = codeLength; } public void setWidth(int width) { this.width = width; } public void setHeight(int height) { this.height = height; } /* * 产生随机数字验证码 */ public String generateRandomNumberCode() { String sRand = ""; Random random = new Random(); for (int i = 0; i < codeLength; i++) { sRand += random.nextInt(10); } return sRand; } /* * 产生随机字母数字混合验证码 */ public String generateRandomMixedCode() { String sRand = ""; Random random = new Random(); for (int i = 0; i < codeLength; i++) { sRand += charArray[random.nextInt(charArray.length)]; } return sRand; } /* * 取得验证码图片 */ public BufferedImage getImage(String checkCode) { // 在内存中创建图象 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 获取图形上下文 Graphics g = image.getGraphics(); // 设定背景色 g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); // 设定字体 g.setFont(new Font("Times New Roman", Font.PLAIN, 18)); // 生成随机类 Random random = new Random(); // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到 g.setColor(getRandColor(160, 200)); for (int i = 0; i < 155; i++) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x, y, x + xl, y + yl); } for (int i = 0; i < checkCode.length(); i++) { // 将认证码显示到图象中 g.setColor(new Color(20 + random.nextInt(110), 20 + random .nextInt(110), 20 + random.nextInt(110))); // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成 g.drawString(String.valueOf(checkCode.charAt(i)), 13 * i + 6, 16); } // 图象生效 g.dispose(); return image; } /* * 给定范围获得随机颜色 */ private Color getRandColor(int fc, int bc) { Random random = new Random(); 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 new Color(r, g, b); } }
2、生成校验码控制器类,其中一个方法产生或刷新校验码图片,另外一个方法校验验证码是否正确,不过校验码是否正确,都会清理掉session中保存的验证码,使得生成的验证码只能使用一次,这是从安全出发采取的一种手段:
@Controller @RequestMapping("/checkCode") public class CheckCodeController { @Autowired private CheckCodeService checkCodeService; /** * 生成校验码图片 * @param request * @param response * @throws IOException */ @RequestMapping("/getImage.do") public void getImage(HttpServletRequest request, HttpServletResponse response) throws IOException { // 禁止缓存 response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "No-cache"); response.setDateHeader("Expires", 0); // 指定生成的响应是图片 response.setContentType("image/jpeg"); //String code = checkCodeService.generateRandomNumberCode(); String code = checkCodeService.generateRandomMixedCode(); // 将生成的验证码保存到Session中 HttpSession session = request.getSession(true); session.setAttribute("checkCode", code); ImageIO.write(checkCodeService.getImage(code),"JPEG",response.getOutputStream()); } /** * 验证校验码 * @param checkcode * @return 校验码正确返回true */ @ResponseBody @RequestMapping("/validate.do") public boolean validate(String checkcode, HttpServletRequest request){ HttpSession session = request.getSession(false); if(session == null){ return false; } String code = (String)session.getAttribute("checkCode"); session.removeAttribute("checkCode"); if(checkcode!=null && checkcode.length()>0 && checkcode.toUpperCase().equals(code)){ return true; }else{ return false; } } }
3、前端测试代码,校验成功就转向成功的地址,校验失败,重新获取校验码图片,注意修改测试中图片已经ajax的链接地址:
test 请输入校验码: