Web验证码的实现方法(3)---开源组件Kaptcha

来源:互联网 发布:未来影响现在知乎 编辑:程序博客网 时间:2024/05/18 21:12

Kapatcha组件

Kaptcha组件实现更多功能的验证码功能,可以调整验证码的大小,图片背景,干扰线条颜色形状等,非常方便。有”加减法验证模式“和“中文模式”。

1,jsp部分

1.1--index.jsp

body>    <h1>Kapatcha验证码</h1>     <img alt="random" src="randomcode.jpg" onclick="changeR(this)" style="cursor: pointer;"><form action="check.jsp"><input type="text" name="r" value=""><input type="submit" value="submit"></form><br>  </body>

1.2--check.jsp

<%    String result = (String)request.getSession().getAttribute("KAPTCHA_SESSION_KEY");    String check = request.getParameter("r");    if(result.equals(check)){    out.println("验证码正确");    }else     out.println("验证码错误"); %>

2,--Servlet部分

2.1--加发求和验证码

这个也是要先导入jar包反正该项目的WEBROOT目录的lib包中
下载地址:目前未审核成功,日后加上,百度上也可以搜到,效果一样
package servlet;import com.google.code.kaptcha.Producer;import com.google.code.kaptcha.util.Config;import java.awt.image.BufferedImage;import java.io.IOException;import java.util.Enumeration;import java.util.Properties;import javax.imageio.ImageIO;import javax.servlet.Servlet;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;public class KaptchaServlet extends HttpServlet implements Servlet {private Properties props;//类似于map,有键值映射关系private Producer kaptchaProducer;private String sessionKeyValue;public KaptchaServlet() {this.props = new Properties();this.kaptchaProducer = null;this.sessionKeyValue = null;}public void init(ServletConfig conf) throws ServletException {super.init(conf);//设置用户缓存为false,用系统缓存防止图片过大导致内存溢出ImageIO.setUseCache(false);Enumeration initParams = conf.getInitParameterNames();while (initParams.hasMoreElements()) {String key = (String) initParams.nextElement();String value = conf.getInitParameter(key);this.props.put(key, value);}Config config = new Config(this.props);this.kaptchaProducer = config.getProducerImpl();this.sessionKeyValue = config.getSessionKey();}public void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {//代理服务器端防止缓冲resp.setDateHeader("Expires", 0L);resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");resp.addHeader("Cache-Control", "post-check=0, pre-check=0");resp.setHeader("Pragma", "no-cache");//设置内容格式为图片resp.setContentType("image/jpeg");//获得创建的两个随机数,并分离String capText = this.kaptchaProducer.createText();String s1 = capText.substring(0, 1);String s2 = capText.substring(1, 2);int r = Integer.valueOf(s1).intValue() + Integer.valueOf(s2).intValue();//计算结果存入Session的Attribute中req.getSession().setAttribute(this.sessionKeyValue, String.valueOf(r));//设置图片显示内容BufferedImage bi = this.kaptchaProducer.createImage(s1+"+"+s2+"=?");//获得response的输出流ServletOutputStream out = resp.getOutputStream();//绘制图片ImageIO.write(bi, "jpg", out);try {out.flush();} finally {out.close();}}}

2.2--中文验证码

package servlet;import java.util.Random;import com.google.code.kaptcha.text.TextProducer;import com.google.code.kaptcha.util.Configurable;public class ChineseText extends Configurable implements TextProducer {//获得中文验证码文字public String getText() {int length = getConfig().getTextProducerCharLength();//char[] charS = getConfig().getTextProducerCharString();String[] s = new String[]{"慕","课","网","教","程","验","证","码","实","例"};Random rand = new Random();StringBuffer sb = new StringBuffer();for(int i = 0; i < length; i++){int ind = rand.nextInt(s.length);sb.append(s[ind]);}return sb.toString();}/*获得数字英文大写字母验证码 */public String getText1() {int length = getConfig().getTextProducerCharLength();String finalWord = "", firstWord = "";int tempInt = 0;String[] array = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9","a", "b", "c", "d", "e", "f" };Random rand = new Random();for (int i = 0; i < length; i++) {switch (rand.nextInt(array.length)) {//16以内的随机数case 1:tempInt = rand.nextInt(26) + 65;//A~Z的ASCii码对应的数值firstWord = String.valueOf((char) tempInt);//转化成字符型在转化成字符串型break;case 2:int r1,r2,r3,r4;String strH,strL;// high&lowr1 = rand.nextInt(3) + 11; // 前闭后开[11,14)if (r1 == 13) {r2 = rand.nextInt(7);//[0,7)} else {r2 = rand.nextInt(16);//[0,16)}r3 = rand.nextInt(6) + 10;//[10,16)if (r3 == 10) {r4 = rand.nextInt(15) + 1;} else if (r3 == 15) {r4 = rand.nextInt(15);} else {r4 = rand.nextInt(16);//[0,16)}strH = array[r1] + array[r2];strL = array[r3] + array[r4];byte[] bytes = new byte[2];//16表示strH是十六进制,并返回十进制的数bytes[0] = (byte) (Integer.parseInt(strH, 16));bytes[1] = (byte) (Integer.parseInt(strL, 16));firstWord = new String(bytes);break;default:tempInt = rand.nextInt(10) + 48;//[48,58)对应ASCii码0~9firstWord = String.valueOf((char) tempInt);break;}finalWord += firstWord;}return finalWord;}}


3--web.xml部分

这个比较多,基本上能用到的功能都给出来了
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.4" 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">  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list>  <!-- 随机验证码的类路径  com.google.code.kaptcha.servlet.KaptchaServlet 当改为中文验证码时候要设置为此 -->  <servlet>  <servlet-name>Kaptcha</servlet-name>  <servlet-class>servlet.KaptchaServlet</servlet-class>  <init-param><description>图片边框,合法值:yes , no</description><param-name>kaptcha.border</param-name><param-value>yes</param-value></init-param><init-param><description>边框颜色,合法值: r,g,b (and optional alpha) 或者white,black,blue.</description><param-name>kaptcha.border.color</param-name><param-value>black</param-value></init-param><init-param><description>边框厚度,合法值:>0</description><param-name>kaptcha.border.thickness</param-name><param-value>1</param-value></init-param><init-param><description>图片宽 200</description><param-name>kaptcha.image.width</param-name><param-value>200</param-value></init-param><init-param><description>图片高 50</description><param-name>kaptcha.image.height</param-name><param-value>50</param-value></init-param><init-param><description>图片实现类</description><param-name>kaptcha.producer.impl</param-name><param-value>com.google.code.kaptcha.impl.DefaultKaptcha</param-value></init-param><init-param><description>文本实现类</description><param-name>kaptcha.textproducer.impl</param-name><param-value>
<span style="white-space:pre"></span><!-- 当为自定义中文验证码设置为servle.ChineseText -->
<span style="white-space:pre"></span>servlet.ChineseText<!--加减法时候设置为此 com.google.code.kaptcha.text.impl.DefaultTextCreator --></param-value></init-param><init-param><description>文本集合,验证码值从此集合中获取</description><param-name>kaptcha.textproducer.char.string</param-name><param-value>1234567890</param-value>  <!--<param-value>abcde2345678gfynmnpwx</param-value>--><!--<param-value>慕课网教程验证码实例</param-value> --></init-param><init-param><description>验证码长度 5</description><param-name>kaptcha.textproducer.char.length</param-name><param-value>2</param-value></init-param><init-param><description>字体 Arial, Courier</description><param-name>kaptcha.textproducer.font.names</param-name><param-value>Arial, Courier</param-value></init-param><init-param><description>字体大小 40px.</description><param-name>kaptcha.textproducer.font.size</param-name><param-value>40</param-value></init-param><init-param><description>字体颜色,合法值: r,g,b 或者 white,black,blue.</description><param-name>kaptcha.textproducer.font.color</param-name><param-value>black</param-value></init-param><init-param><description>文字间隔 2</description><param-name>kaptcha.textproducer.char.space</param-name><param-value>2</param-value></init-param><init-param><description>干扰实现类</description><param-name>kaptcha.noise.impl</param-name><param-value><!-- com.google.code.kaptcha.impl.NoNoise -->com.google.code.kaptcha.impl.DefaultNoise</param-value></init-param><init-param><description>干扰颜色,合法值: r,g,b 或者 white,black,blue.</description><param-name>kaptcha.noise.color</param-name><param-value>black</param-value></init-param><init-param><description>图片样式: 水纹com.google.code.kaptcha.impl.WaterRipple鱼眼com.google.code.kaptcha.impl.FishEyeGimpy阴影com.google.code.kaptcha.impl.ShadowGimpy</description><param-name>kaptcha.obscurificator.impl</param-name><param-value>com.google.code.kaptcha.impl.WaterRipple</param-value></init-param><init-param><description>背景实现类</description><param-name>kaptcha.background.impl</param-name><param-value>com.google.code.kaptcha.impl.DefaultBackground</param-value></init-param><init-param><description>背景颜色渐变,开始颜色</description><param-name>kaptcha.background.clear.from</param-name><param-value>green</param-value></init-param><init-param><description>背景颜色渐变,结束颜色</description><param-name>kaptcha.background.clear.to</param-name><param-value>white</param-value></init-param><init-param><description>文字渲染器</description><param-name>kaptcha.word.impl</param-name><param-value>com.google.code.kaptcha.text.impl.DefaultWordRenderer</param-value></init-param><init-param><description>session中存放验证码的key键</description><param-name>kaptcha.session.key</param-name><param-value>KAPTCHA_SESSION_KEY</param-value></init-param><init-param><description>The date the kaptcha is generated is put into theHttpSession. This is the key value for that item in thesession.</description><param-name>kaptcha.session.date</param-name><param-value>KAPTCHA_SESSION_DATE</param-value></init-param>  </servlet>  <servlet-mapping>  <servlet-name>Kaptcha</servlet-name>  <url-pattern>/randomcode.jpg</url-pattern>  </servlet-mapping></web-app>

总结:

kaptcha组件使用更加方便,自定义功能很多,这次实现了普通验证码功能和加法验证码功能,还可以设置自定义中文验证码,非常方便。





1 0
原创粉丝点击