jsp 用 kaptcha 外掛程式產生數字運算圖形驗證碼

來源:互聯網
上載者:User

1.從官網https://code.google.com/p/kaptcha/下載kaptcha壓縮檔,解壓檔案后里面有一個war檔案,開啟Eclipse/MyEclipse將其import進去,然後部署到伺服器,在瀏覽器輸入url即可看到kaptcha官方提供的基本demo的運行情況,現在將其改為加法計算驗證。

2.首先查看web.xml檔案發現用來產生驗證碼的servlet為KaptchaServlet


3.找到KaptchaServlet.class檔案,然後進行反編譯。

4.建立一個自己的驗證碼MyKaptchaServlet,將反編譯得到的源碼拷貝進來。

5.對MyKaptchaServlet做如下修改。

修改後MyKaptchaServlet.java代碼如下:


package com.xhc.kaptchaServlet;

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.Date;
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 MyKaptchaServlet extends HttpServlet implements Servlet {
 private Properties props;
 private Producer kaptchaProducer;
 private String sessionKeyValue;
 private String sessionKeyDateValue;

 public MyKaptchaServlet() {
  this.props = new Properties();

  this.kaptchaProducer = null;

  this.sessionKeyValue = null;

  this.sessionKeyDateValue = null;
 }

 public void init(ServletConfig conf) throws ServletException {
  super.init(conf);

  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();
  this.sessionKeyDateValue = config.getSessionDate();
 }

 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 str1 = capText.substring(0, 2);
  String str2 = capText.substring(2, 4);
  int result = Integer.valueOf(str1) + Integer.valueOf(str2);
  req.getSession().setAttribute(this.sessionKeyValue, result+"");

  req.getSession().setAttribute(this.sessionKeyDateValue, new Date());

  BufferedImage bi = this.kaptchaProducer.createImage(str1 + "+" + str2
    + "=?");

  ServletOutputStream out = resp.getOutputStream();

  ImageIO.write(bi, "jpg", out);
 }
}


6.修改web.xml設定檔,將servlet-class指定到MyKaptchaServlet


參考官方文檔

https://code.google.com/p/kaptcha/wiki/ConfigParameters將其他屬性也配置進去,修改後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> -->
<servlet-class>com.xhc.kaptchaServlet.MyKaptchaServlet</servlet-class>
<!-- For a complete list of Init Parameters, please see: http://code.google.com/p/kaptcha/wiki/ConfigParameters -->
<!-- 驗證碼邊界,合法值yes or no -->
<init-param>
<param-name>kaptcha.border</param-name>
<param-value>yes</param-value>
</init-param>
<!-- 邊界顏色,合法值 r,g,b (and optional alpha) or white,black,blue -->
<init-param>
<param-name>kaptcha.border.color</param-name>
<param-value>black</param-value>
</init-param>
<!-- 邊界厚度,合法值 大於0 -->
<init-param>
<param-name>kaptcha.border.thickness</param-name>
<param-value>1</param-value>
</init-param>
<!-- 驗證碼圖片寬度 -->
<init-param>
<param-name>kaptcha.image.width</param-name>
<param-value>200</param-value>
</init-param>
<!-- 驗證碼圖片高度 -->
<init-param>
<param-name>kaptcha.image.height</param-name>
<param-value>50</param-value>
</init-param>
<!-- 驗證碼圖片產生類,預設由DefaultKaptcha類產生,可以自己寫一個圖片產生類,需要實現Producer介面並繼承Configurable
類 -->
<init-param>
<param-name>kaptcha.producer.impl</param-name>
<param-value>com.google.code.kaptcha.impl.DefaultKaptcha</param-value>
</init-param>
<!-- 驗證碼產生類,預設由DefaultTextCreator類產生,可以自己寫一個驗證碼產生類,需要實現TextProducer介面並繼承Configurable
類 -->
<init-param>
<param-name>kaptcha.textproducer.impl</param-name>
<param-value>com.google.code.kaptcha.text.impl.DefaultTextCreator</param-value>
</init-param>
<!-- 用來產生驗證碼的字元集 -->
<init-param>
<param-name>kaptcha.textproducer.char.string</param-name>
<param-value>01234565789</param-value>
</init-param>
<!-- 產生驗證碼的長度 -->
<init-param>
<param-name>kaptcha.textproducer.char.length</param-name>
<param-value>4</param-value>
</init-param>
<!-- 驗證碼字型,多個值用逗號隔開 -->
<init-param>
<param-name>kaptcha.textproducer.font.names</param-name>
<param-value>Arial,Courier</param-value>
</init-param>
<!-- 字型大小 -->
<init-param>
<param-name>kaptcha.textproducer.font.size</param-name>
<param-value>40</param-value>
</init-param>
<!-- 字型顏色 -->
<init-param>
<param-name>kaptcha.textproducer.font.color</param-name>
<param-value>blue</param-value>
</init-param>
<!-- 驗證碼字元間隔 -->
<init-param>
<param-name>kaptcha.textproducer.char.space</param-name>
<param-value>5</param-value>
</init-param>
<!-- 圖片幹擾產生類,預設由DefaultNoise類產生,可以自己寫一個圖片幹擾類,需要實現NoiseProducer介面並繼承Configurable
類 -->
<init-param>
<param-name>kaptcha.noise.impl</param-name>
<param-value>com.google.code.kaptcha.impl.DefaultNoise</param-value>
</init-param>
<!-- 幹擾顏色 -->
<init-param>
<param-name>kaptcha.noise.color</param-name>
<param-value>yellow</param-value>
</init-param>
<!--擷取扭曲的不同風格的驗證碼,官方實現的有ShadowGimpy,FishEyeGimpy,WaterRipple,其中用來FishEyeGimpy之後上面設定的幹擾線不起作用-->
<init-param>
<param-name>kaptcha.obscurificator.impl</param-name>
<param-value>com.google.code.kaptcha.impl.FishEyeGimpy</param-value>
</init-param>
<!--漸層背景色,初始顏色 -->
<init-param>
<param-name>kaptcha.background.clear.from</param-name>
<param-value>gray</param-value>
</init-param>
<!-- 漸層北京市,最終顏色 -->
<init-param>
<param-name>kaptcha.background.clear.to</param-name>
<param-value>white</param-value>
</init-param>
<!-- 文字渲染器 -->
<init-param>
<param-name>kaptcha.word.impl</param-name>
<param-value>com.google.code.kaptcha.text.impl.DefaultWordRenderer</param-value>
</init-param>
<init-param>
<param-name>kaptcha.session.key</param-name>
<param-value>KAPTCHA_SESSION_KEY</param-value>
</init-param>
<init-param>
<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>/Kaptcha.jpg</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>KaptchaExample.jsp</welcome-file>
</welcome-file-list>
</web-app>


7.效果圖

java自動產生驗證碼外掛程式-kaptcha


 kaptcha一個很好用的驗證碼外掛程式,java版的,很不錯的一個外掛程式,只用簡單的在web.xml中設定幾個屬性,一個很漂亮的驗證碼就出來了。其他的參數都可以自己設定,最牛的就是提供了介面,可以自己定義哦。

html頁面代碼

<form action="submit.action">
    <img src="kaptcha.jpg" /> <input type="text" name="kaptcha" value="" />
</form>

web.xml配置代碼

<servlet>
        <servlet-name>Kaptcha</servlet-name>
        <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
        <servlet-name>Kaptcha</servlet-name>
        <url-pattern>/kaptcha.jpg</url-pattern>
</servlet-mapping>

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.");
}

點擊顯示代碼 重新整理方法 js方法

<img src="/kaptcha" width="200" id="kaptchaImage" />
<script type="text/javascript">
    $(function(){
        $('#kaptchaImage').click(function () {
            $(this).attr('src', '/kaptcha.jpg?' + Math.floor(Math.random()*100) );
        })
    });
</script>
<br /><small>Can't read the image? Click it to get a new one.</small>

其他參數設定

<init-param>  
            <param-name>kaptcha.border</param-name>  
            <param-value>yes</param-value>  
        </init-param>  
        <init-param>  
            <param-name>kaptcha.border.color</param-name>  
            <param-value>105,179,90</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.image.width</param-name>  
            <param-value>500</param-value>  
        </init-param>  
        <init-param>  
            <param-name>kaptcha.image.height</param-name>  
            <param-value>300</param-value>  
        </init-param>  
        <init-param>  
            <param-name>kaptcha.textproducer.font.size</param-name>  
            <param-value>90</param-value>  
        </init-param>  
        <init-param>  
            <param-name>kaptcha.session.key</param-name>  
            <param-value>code</param-value>  
        </init-param>  
        <init-param>  
            <param-name>kaptcha.textproducer.char.length</param-name>  
            <param-value>4</param-value>  
        </init-param>  
        <init-param>  
            <param-name>kaptcha.textproducer.font.names</param-name>  
            <param-value>宋體,楷體,微軟雅黑</param-value>  
        </init-param>


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.