`

simpeCaptha验证码并自己附加加减运算

 
阅读更多
这个是验证码的开源框架 。
首先import SimpleCaptha  jar .

然后web.xml

引用
<servlet>    
       <servlet-name>StickyCaptcha</servlet-name>    
       <servlet-class>nl.captcha.servlet.SimpleCaptchaServlet</servlet-class>    
        <init-param>    
          <param-name>width</param-name>    
           <param-value>150</param-value>    
        </init-param>    
        <init-param>    
           <param-name>height</param-name>    
            <param-value>35</param-value>    
        </init-param>    
       <init-param>  
         <param-name>text</param-name>  
         <param-value>word:3,number:3</param-value>  
    </init-param>  
   </servlet>    
    <servlet-mapping>     
        <servlet-name>StickyCaptcha</servlet-name>    
      <url-pattern>/stickyImg</url-pattern>    
   </servlet-mapping> 
 


index.jsp

引用
<img src="/Validation/stickyImg" />  

    <form action="/Validation/captchaSubmit.jsp" method="post">    
        <input name="answer" />    
        <input type="submit" name="submit"/>    
</form> 
Validation工程名

然后验证。。。
captchaSubmit.jsp

引用
<%@ page import="nl.captcha.Captcha" %>    
   <%    
   nl.captcha.Captcha captcha = (nl.captcha.Captcha) session.getAttribute(Captcha.NAME);    
  request.setCharacterEncoding("UTF-8");    
    String answer = request.getParameter("answer");    
   if (captcha.isCorrect(answer)) { %>    
       <b>Correct!</b>    
<% } %>  



如果想扩展和详细了解,可以反编译jar看或者。
http://www.iteye.com/topic/790024
http://xiayingjie.iteye.com/blog/790038


如果想可以用加减简单运算验证。则可以扩展这个核心类。

package util;
import java.awt.Color;
import java.awt.Font;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nl.captcha.backgrounds.GradiatedBackgroundProducer;
import nl.captcha.gimpy.BlockGimpyRenderer;
import nl.captcha.servlet.CaptchaServletUtil;
import nl.captcha.text.producer.ChineseTextProducer;
import nl.captcha.text.producer.DefaultTextProducer;
import nl.captcha.text.renderer.DefaultWordRenderer;
import nl.captcha.text.renderer.WordRenderer;

public class CalculateCaptcha extends HttpServlet {

	private static final String PARAM_HEIGHT = "height"; // 高度 默认为50

	private static final String PARAM_WIDTH = "width";// 宽度 默认为200

	private static final String PAEAM_NOISE = "noise";// 干扰线条 默认是没有干扰线条

	private static final String PAEAM_TEXT = "text";// 文本

	private static final String PAEAM_CAL = "calculate";// 算数
	
	protected int _width = 200;
	protected int _height = 50;
	protected boolean _noise = false;
	protected String _text = null;
	protected String _cal = "0";

	@Override
	public void init() throws ServletException {
		if (getInitParameter(PARAM_HEIGHT) != null) {
			_height = Integer.valueOf(getInitParameter(PARAM_HEIGHT));
		}

		if (getInitParameter(PARAM_WIDTH) != null) {
			_width = Integer.valueOf(getInitParameter(PARAM_WIDTH));
		}

		if (getInitParameter(PAEAM_NOISE) != null) {
			_noise = Boolean.valueOf(getInitParameter(PAEAM_NOISE));
		}

		if (getInitParameter(PAEAM_TEXT) != null) {
			_text = String.valueOf(getInitParameter(PAEAM_TEXT));
		}
		if (getInitParameter(PAEAM_CAL) != null) {
			_cal = String.valueOf(getInitParameter(PAEAM_CAL));
		}
	}

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		OcjCaptcha.Builder builder = new OcjCaptcha.Builder(_width, _height);
		// 增加边框
		builder.addBorder();
		// 是否增加干扰线条
		if (_noise == true)
			builder.addNoise();
		// ----------------自定义字体大小-----------
		// 自定义设置字体颜色和大小 最简单的效果 多种字体随机显示
		List<Font> fontList = new ArrayList<Font>();
		fontList.add(new Font("Courier", Font.BOLD, 40));
		DefaultWordRenderer dwr = new DefaultWordRenderer(Color.green, fontList);
		WordRenderer wr = dwr;
		// 增加文本,默认为5个随机字符.
		if ("1".equals(_cal)) {
			char[] numbers = new char[] {'0','1', '2', '3', '4', '5', '6','7', '8' };
			builder.addText(new DefaultTextProducer(1,numbers), wr);
			char[] operators = new char[] {'+','-'};
			builder.addText(new DefaultTextProducer(1,operators), wr);
			builder.addText(new DefaultTextProducer(1,numbers), wr);
		}else if (_text != null){
			String[] ts = _text.split(",");
			for (int i = 0; i < ts.length; i++) {
				String[] ts1 = ts[i].split(":");
				if ("chinese".equals(ts1[0])) {
					builder.addText(
							new ChineseTextProducer(Integer.parseInt(ts1[1])),
							wr);
				} else if ("number".equals(ts1[0])) {
					// 这里没有0和1是为了避免歧义 和字母I和O
					char[] numberChar = new char[] {'0','1', '2', '3', '4', '5', '6',
							'7', '8' };
					builder.addText(
							new DefaultTextProducer(Integer.parseInt(ts1[1]),
									numberChar), wr);
				}  else if ("word".equals(ts1[0])) {
					// 原理同上
					char[] numberChar = new char[] { 'a', 'b', 'c', 'd', 'e',
							'f', 'g', 'h', 'k', 'm', 'n', 'p', 'r', 'w', 'x',
							'y' };
					builder.addText(
							new DefaultTextProducer(Integer.parseInt(ts1[1]),
									numberChar), wr);
				}else {
					builder.addText(
							new DefaultTextProducer(Integer.parseInt(ts1[1])),
							wr);
				}
			}

		}else{
			builder.addText();
		}

		// 设置背景渐进效果 以及颜色 form为开始颜色,to为结束颜色
		GradiatedBackgroundProducer gbp = new GradiatedBackgroundProducer();
		gbp.setFromColor(Color.yellow);
		gbp.setToColor(Color.red);
		// 无渐进效果,只是填充背景颜色
		builder.addBackground(gbp);
		builder.gimp(new BlockGimpyRenderer(1));
		OcjCaptcha captcha = builder.build();
		CaptchaServletUtil.writeImage(resp, captcha.getImage());
		//如果算数支持.
		if("1".equals(_cal)){
			String anstr=captcha.getAnswer();
			String oper=anstr.indexOf('+')!=-1?"+":"-";
			String anstrs[]=anstr.split(oper);
			Integer result =0;
			switch(oper){
			case "+":
				result=Integer.parseInt(anstrs[0])+Integer.parseInt(anstrs[1]);
				break;
			case "-":
				result=Integer.parseInt(anstrs[0])-Integer.parseInt(anstrs[1]);
				break;
			}
			captcha.setAnswer(String.valueOf(result));
		}
		req.getSession().setAttribute(OcjCaptcha.NAME, captcha);
	}

}



配置文件web.xml
引用
<servlet>    
       <servlet-name>StickyCaptcha</servlet-name>    
       <servlet-class>util.CalculateCaptcha</servlet-class>    
        <init-param>    
          <param-name>width</param-name>    
           <param-value>100</param-value>    
        </init-param>    
        <init-param>    
           <param-name>height</param-name>    
            <param-value>35</param-value>    
        </init-param>    
       <init-param>  
         <param-name>text</param-name>  
         <param-value>word:0,number:0</param-value>  
       </init-param>  
        <init-param>    
           <param-name>calculate</param-name>    
            <param-value>1</param-value>    
        </init-param>  
   </servlet>    
    <servlet-mapping>     
        <servlet-name>StickyCaptcha</servlet-name>    
      <url-pattern>/stickyImg</url-pattern>    
   </servlet-mapping>   


OcjCaptcha 为Captcha加了个

public void setAnswer(String answer) {
		this._builder._answer = answer;
	}


如果页面需要无提交页面就刷新验证码的话,可以使用更改src的方式来实现。不能用ajax实现。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics