Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Wiki Markup
*This page demonstrates how to use jcaptcha in your application*.

...



This tutorial uses the CaptchaService and sub components (see [Architecture overview]).

...



h1. Install

...

Maven2 users

Add the following dependency to your project POM

Code Block
 it


h2. Maven2 users

{tips}
Any release was published since Maven2 is used, but nightly build are available in Archiva :
http://forge.octo.com/archiva/browse/com.octo.captcha/jcaptcha/1.0-SNAPSHOT

In order to get the lastest version you have to add the following repository to your project POM :
http://forge.octo.com/archiva/repository/forge-snapshots
{tips}

Add the following dependency to your project POM
{code}
<dependency>
	<groupId>com.octo.captcha</groupId>
	<artifactId>jcaptcha</artifactId>
	<version>1.0-SNAPSHOT</version>
</dependency>

Without Maven2

...


{code}

h2. Without Maven2

Add jcaptcha-all.jar (provided in [bin-distribution|http://sourceforge.net/project/showfiles.php?group_id=97877&package_id=104743]) and commons-collection-3.2 or greater (not provided see [commons collection |http://commons.apache.org/downloads/download_collections.cgi]) to your application class path, ie in you WEB-INF/lib folder.

h1.

...

 Implement a CaptchaService

...

singleton


{note
:title
=It must be a
Code Block
 singleton}
{note}
{code}
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;
    }
}

Code an image captcha servlet

Code Block
{code}

h1. Code an image captcha servlet

{code}
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();
    }
}
{code}

h1. Add it to your web.xml

...



{code
}
<servlet>
        <servlet-name>jcaptcha</servlet-name>
        <servlet-class>ImageCaptchaServlet</servlet-class>
        <load-on-startup>0</load-on-startup>
    </servlet>
{code}
And

...


{code
}
<servlet-mapping>
        <servlet-name>jcaptcha</servlet-name>
        <url-pattern>/jcaptcha</url-pattern>
    </servlet-mapping>

The form

Provide a form containing the captcha challenge (the image) and an input text for the response

Code Block

{code}

h1. The form

Provide a form containing the captcha challenge (the image) and an input text for the response
{code}
<img src="/jcaptcha">
<input type='text' name='j_captcha_response' value=''>

the validation routine

Handle the post (using a servlet, or whatever).
The validateCaptchaForId method will return true if the response is correct.

Code Block

{code}

h1. the validation routine

Handle the post (using a servlet, or whatever).
The validateCaptchaForId method will return true if the response is correct.
{code}
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
            }

//do something according to the result!

Want some more

Tip
titleTry customization and more integration

Have a look to the modules provided to see how to integrate it with other frameworks :

  • Change the Captcha generation configuration
  • Use JCaptcha with a Spring configuration
    
    {code}
    
    h1. Want some more
    
    {tip:title=Try customization and more integration}
    Have a look to the modules provided to see how to integrate it with other frameworks :
    * [Change the Captcha generation configuration]
    * [Use JCaptcha with a Spring configuration|JCaptcha and the SpringFramework]
    {tip}