Java生成验证码
kaptcha 1.[code="java"] kaptcha一个很好用的验证码插件,java版的,很不错的一个插件,只用简单的在web.xml中设置几个属性,一个很漂亮的验证码就出来了。其他的参数都可以自己设置,最牛的就是提供了接口,可以自己定义哦。 [代码] html代码

[代码] web.xml Kaptcha com.google.code.kaptcha.servlet.KaptchaServlet Kaptcha /kaptcha.jpg [代码] java代码 String kaptchaExpected = (String)request.getSession() .getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); String kaptchaReceived = request.getParameter("kaptcha"); if (kaptchaReceived == null || !kaptchaReceived.equalsIgnoreCase(kaptchaExpected)) { setError("kaptcha", "Invalid validation code."); } [代码] 根据点击显示验证码
Can't read the image? Click it to get a new one. [/code] jcaptcha 2.[code="java"]前言: 现在很多系统和网站使用场景都使用验证码来增强系统安全性。 下面介绍jcaptcha来产生验证码和验证 http://jcaptcha.sourceforge.net/ 下面的程序代码参考和仿照了springside3的实现 1.在web.xml上增加验证码的过滤器 创建验证码图形的Filter jcaptchaFilter /jcaptcha.jpg 验证的Filter jcaptchaFilter /check 自己写用jcaptcha产生验证码和验证实现的filter jcaptchaFilter security.jcaptcha.JCaptchaFilter failureUrl /head.vm 2.获取验证码 在介绍图形码过滤器前,介绍一下jcaptcha产生验证码的api和code 验证码产生和验证需要jcaptcha的com.octo.captcha.service.image.DefaultManageableImageCaptchaService类的服务 产生验证码,并以图片信息输出到客户端 获取验证码的方法: captchaService.getChallengeForID(id) 根据你的id随机产生验证码 代码片段 protected void genernateCaptchaImage(final HttpServletRequest request, final HttpServletResponse response) throws IOException { //设置response,输出图片客户端不缓存 response.setDateHeader("Expires", 1L); response.addHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache, no-store, max-age=0"); response.setContentType("image/jpeg"); ServletOutputStream out = response.getOutputStream(); //获取验证码 try { String captchaId = request.getSession(true).getId(); //用session的id来产生验证码 BufferedImage challenge = (BufferedImage) captchaService.getChallengeForID(captchaId, request.getLocale());//获取验证码 ImageIO.write(challenge, "jpg", out); out.flush(); } catch (CaptchaServiceException e) { System.out.println(e); } finally { out.close(); } } 在显示层,展示验证码 3.验证码验证 在介绍图形码过滤器前,介绍一下jcaptcha产生验证码的api和code 验证码产生和验证需要jcaptcha的com.octo.captcha.service.image.DefaultManageableImageCaptchaService类的服务 产生验证码,并以图片信息输出到客户端 获取验证码的方法: captchaService.validateResponseForID(captchaID, 输入的验证码); 返回值true 表示验证通关,false表示验证还没有通过 代码片段 protected boolean validateCaptchaChallenge(final HttpServletRequest request) { try { //获取产生验证码的id,用session的id来产生验证码 String captchaID = request.getSession().getId(); //获取输入的验证码 String challengeResponse = request.getParameter(captchaParamterName); return captchaService.validateResponseForID(captchaID, challengeResponse); } catch (CaptchaServiceException e) { System.out.println(e); return false; } }[/code]