jcaptcha做jsp彩色驗證碼

來源:互聯網
上載者:User
在做opencms的表單時,使用到了jcaptcha來做驗證碼.簡單看了一下,覺得還不錯,收藏了.今天又進步了一點點,嘿嘿:)

用開源組件jcaptcha做jsp彩色驗證碼

key words: jsp驗證碼 jcaptcha

原文參考 這裡

安裝

Add jcaptcha-all.jar (provided in bin-distribution) and ehcache.jar (not provided see ehcache site) to your application class path, ie in you WEB-INF/lib folder.

執行個體一個jcaptcha服務,注意,必須是單例模式的import com.octo.captcha.service.image.ImageCaptchaService;
import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;

public class CaptchaServiceSingleton {
    
    private static ImageCaptchaService instance = new DefaultManageableImageCaptchaService();
    
    public static ImageCaptchaService getInstance(){
        return instance;
    }
}

注:以上是預設的一個實現,下面是其他更多的實現

  • SimpleListSoundCaptchaEngine   //還可以用聲音,真爽哦
  • SpellerSoundCaptchaEngine
  • SpellerSoundCaptchaEngine
  • DefaultGimpyEngineCaptcha           
  • BaffleListGimpyEngineCaptcha           
  • BasicListGimpyEngineCaptcha           
  • DeformedBaffleListGimpyEngineCaptcha           
  • DoubleRandomListGimpyEngineCaptcha           
  • SimpleListImageCaptchaEngineCaptcha           
  • SimpleFishEyeEngineCaptcha

具體請參考官方說明

編寫一個產生圖片的servlet

import com.octo.captcha.service.CaptchaServiceException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

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 java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ImageCaptchaServlet extends HttpServlet {

    public void init(ServletConfig servletConfig) throws ServletException {

        super.init(servletConfig);

    }

    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        
       byte[] captchaChallengeAsJpeg = null;
       // the output stream to render the captcha image as jpeg into
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
        // get the session id that will identify the generated captcha. 
        //the same id must be used to validate the response, the session id is a good candidate!
        String captchaId = httpServletRequest.getSession().getId();
        // call the ImageCaptchaService getChallenge method
            BufferedImage challenge =
                    CaptchaServiceSingleton.getInstance().getImageChallengeForID(captchaId,
                            httpServletRequest.getLocale());
            
            // a jpeg encoder
            JPEGImageEncoder jpegEncoder =
                    JPEGCodec.createJPEGEncoder(jpegOutputStream);
            jpegEncoder.encode(challenge);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        } catch (CaptchaServiceException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

        // flush it in the response
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }
}

為servlet修改web.xml設定檔<servlet>
        <servlet-name>jcaptcha</servlet-name>
        <servlet-class>ImageCaptchaServlet</servlet-class>
        <load-on-startup>0</load-on-startup>
    </servlet>

<servlet-mapping>
        <servlet-name>jcaptcha</servlet-name>
        <url-pattern>/jcaptcha</url-pattern>
</servlet-mapping>

編寫你的用戶端的展示<img src="jcaptcha">
<input type='text' name='j_captcha_response' value=''>

上面的src="jcaptcha"  就是調用了上面的servlet,text裡是使用者填寫的確認驗證碼

後台邏輯驗證Boolean isResponseCorrect =Boolean.FALSE;
           //remenber that we need an id to validate!
           String captchaId = httpServletRequest.getSession().getId();
           //retrieve the response
           String response = httpServletRequest.getParameter("j_captcha_response");
           // Call the Service method
            try {
                isResponseCorrect = CaptchaServiceSingleton.getInstance().validateResponseForID(captchaId,
                        response);
            } catch (CaptchaServiceException e) {
                 //should not happen, may be thrown if the id is not valid 
            }

OK,大功告成了.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.