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

Kapatcha组件

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

1,jsp部分

1.1--index.jsp

body>
    <h1>Kapatcha验证码</h1> 
    <img alt="random" src="randomcode.jpg" οnclick="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&low
				r1 = 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~9
				firstWord = 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 the
				HttpSession. This is the key value for that item in the
				session.
			</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组件使用更加方便,自定义功能很多,这次实现了普通验证码功能和加法验证码功能,还可以设置自定义中文验证码,非常方便。





  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值