web页面 验证码 生成
kaptcha 是一个非常实用的验证码生成工具。有了它,你可以生成各种样式的验证码,因为它是可配置的。kaptcha工作的原理是调用 com.google.code.kaptcha.servlet.KaptchaServlet,生成一个图片。同时将生成的验证码字符串放到 HttpSession中。
使用kaptcha可以方便的配置:
- 验证码的字体
- 验证码字体的大小
- 验证码字体的字体颜色
- 验证码内容的范围(数字,字母,中文汉字!)
- 验证码图片的大小,边框,边框粗细,边框颜色
- 验证码的干扰线(可以自己继承com.google.code.kaptcha.NoiseProducer写一个自定义的干扰线)
- 验证码的样式(鱼眼样式、3D、普通模糊……当然也可以继承com.google.code.kaptcha.GimpyEngine自定义样式)
……
详细信息请看下面的web.xml文件
下面介绍一下用法:
1.首先去官网下载jar:http://code.google.com/p/kaptcha/
2.建立一个web项目,导入kaptcha-2.3.jar到环境变量中。
3.配置web.xml文件
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <servlet> <servlet-name>Kaptcha</servlet-name> <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class> <!-- For a complete list of Init Parameters, please see: http://code.google.com/p/kaptcha/wiki/ConfigParameters --> <init-param> <param-name>kaptcha.border</param-name> <param-value>no</param-value> </init-param> <init-param> <param-name>kaptcha.textproducer.font.color</param-name> <param-value>black</param-value> </init-param> <init-param> <param-name>kaptcha.textproducer.char.space</param-name> <param-value>5</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Kaptcha</servlet-name> <url-pattern>/Kaptcha.jpg</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>KaptchaExample.jsp</welcome-file> </welcome-file-list> </web-app>
4.jsp页面
KaptchaExample.jsp:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <%@ page language="java" contentType="text/html; charset=UTF-8" %> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Kaptcha Example</title> </head> <script type="text/javascript"> $(function() { $('#kaptchaImage').click(function() {$(this).attr('src','kaptcha.jpg?' + Math.floor(Math.random() * 100));}); }); </script> <body> Enter in the <a href="http://code.google.com/p/kaptcha/">Kaptcha</a> to see if it matches what is stored in the session attributes. <table> <tr> <td><img src="Kaptcha.jpg" id="kaptchaImage" ></td> <td valign="top"> <form method="POST"> <br>sec code:<input type="text" name="kaptchafield"><br /> <input type="submit" name="submit"> </form> </td> </tr> </table> <br /><br /><br /><br /> <% String c = (String)session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); String parm = (String) request.getParameter("kaptchafield"); out.println("Parameter: " + parm + " ? Session Key: " + c + " : "); if (c != null && parm != null) { if (c.equals(parm)) { out.println("<b>true</b>"); } else { out.println("<b>false</b>"); } } %> </body> </html>
上面的配置在普通jsp环境下面是有效的,如果在spring mvc环境下,则取不到session值,对于sping mvc环境验证码配置如下:
1.不用在web.xml进行相关配置,在applicationContext.xml中配置
<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha"> <property name="config"> <bean class="com.google.code.kaptcha.util.Config"> <constructor-arg> <props> <prop key="kaptcha.border">no</prop> <prop key="kaptcha.border.color">105,179,90</prop> <prop key="kaptcha.textproducer.font.color">red</prop> <prop key="kaptcha.image.width">250</prop> <prop key="kaptcha.textproducer.font.size">90</prop> <prop key="kaptcha.image.height">90</prop> <prop key="kaptcha.session.key">code</prop> <prop key="kaptcha.textproducer.char.length">4</prop> <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop> </props> </constructor-arg> </bean> </property> </bean>
2.新建生成图片控制类
package com.google.code.kaptcha; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.Constants; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/") public class CaptchaImageCreateController { private Producer captchaProducer = null; @Autowired public void setCaptchaProducer(Producer captchaProducer) { this.captchaProducer = captchaProducer; } @RequestMapping("/captcha-image") public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { // Set to expire far in the past. response.setDateHeader("Expires", 0); // Set standard HTTP/1.1 no-cache headers. response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // Set IE extended HTTP/1.1 no-cache headers (use addHeader). response.addHeader("Cache-Control", "post-check=0, pre-check=0"); // Set standard HTTP/1.0 no-cache header. response.setHeader("Pragma", "no-cache"); // return a jpeg response.setContentType("image/jpeg"); // create the text for the image String capText = captchaProducer.createText(); // store the text in the session request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText); // create the image with the text BufferedImage bi = captchaProducer.createImage(capText); ServletOutputStream out = response.getOutputStream(); // write the data out ImageIO.write(bi, "jpg", out); try { out.flush(); } finally { out.close(); } return null; } }
3.前台调用方式
<div class="chknumber"> <label>验证码: <input name="kaptcha" type="text" id="kaptcha" maxlength="4" class="chknumber_input" /> </label> <img src="/ClinicCountManager/captcha-image.do" width="55" height="20" id="kaptchaImage" style="margin-bottom: -3px"/> <script type="text/javascript"> $(function(){ $('#kaptchaImage').click(function () {//生成验证码 $(this).hide().attr('src', '/ClinicCountManager/captcha-image.do?' + Math.floor(Math.random()*100) ).fadeIn(); }) }); </script> </div>
4.取验证码的方式
String code = (String)session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
啦啦啦
kaptcha.border 是否有边框 默认为true 我们可以自己设置yes,no kaptcha.border.color 边框颜色 默认为Color.BLACK kaptcha.border.thickness 边框粗细度 默认为1 kaptcha.producer.impl 验证码生成器 默认为DefaultKaptcha kaptcha.textproducer.impl 验证码文本生成器 默认为DefaultTextCreator kaptcha.textproducer.char.string 验证码文本字符内容范围 默认为abcde2345678gfynmnpwx kaptcha.textproducer.char.length 验证码文本字符长度 默认为5 kaptcha.textproducer.font.names 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize) kaptcha.textproducer.font.size 验证码文本字符大小 默认为40 kaptcha.textproducer.font.color 验证码文本字符颜色 默认为Color.BLACK kaptcha.textproducer.char.space 验证码文本字符间距 默认为2 kaptcha.noise.impl 验证码噪点生成对象 默认为DefaultNoise kaptcha.noise.color 验证码噪点颜色 默认为Color.BLACK kaptcha.obscurificator.impl 验证码样式引擎 默认为WaterRipple kaptcha.word.impl 验证码文本字符渲染 默认为DefaultWordRenderer kaptcha.background.impl 验证码背景生成器 默认为DefaultBackground kaptcha.background.clear.from 验证码背景颜色渐进 默认为Color.LIGHT_GRAY kaptcha.background.clear.to 验证码背景颜色渐进 默认为Color.WHITE kaptcha.image.width 验证码图片宽度 默认为200 kaptcha.image.height 验证码图片高度 默认为50 1.导入kaptcha9.jar 2.<bean id="captcha" class="com.google.code.kaptcha.servlet.KaptchaExtend"> <constructor-arg> <props> <!-- 是否有边框 边框颜色 边框粗细 --> <prop key="kaptcha.border">yes</prop> <prop key="kaptcha.border.color">105,179,90</prop> <prop key="kaptcha.border.thickness">20</prop> <prop key="kaptcha.textproducer.font.color">black</prop> <prop key="kaptcha.image.width">200</prop> <prop key="kaptcha.image.height">50</prop> <prop key="kaptcha.textproducer.font.size">40</prop> <!-- 验证码在session中存储时的key:session.setAttribute("xxx",xxxx); --> <prop key="kaptcha.session.key">code</prop> <prop key="kaptcha.textproducer.char.length">4</prop> <prop key="kaptcha.textproducer.font.names">Arial,Courier</prop> <prop key="kaptcha.background.clear.from">black</prop> <prop key="kaptcha.background.clear.to">255,0,0</prop> </props> </constructor-arg> </bean> 3. @... public class XXController{ //在Controller中注入验证码生成器 @Autowired private KaptchaExtend ke; @RequestMapping("/kap2") public String kaptcha2(HttpServletRequest req,HttpServletResponse resp,HttpSession s){ try { ke.captcha(req, resp);//生成验证码,并写出验证码图片 System.out.println("code:"+s.getAttribute("code")); } return null; } } *需要jdk7
啦啦啦