Blue Flower

SimpleCaptcha


Installing SimpleCaptcha is no different than installing most other libraries for a J2EE container: a jar is deployed to WEB-INF/lib and web.xml is updated. These steps are described in detail below.

1. Download SimpleCaptcha
2. Copy the jar file to your WEB-INF/lib directory
3. Add a mapping to web.xml. There are three servlets provided out of the box: StickyCaptchaServlet, SimpleCaptchaServlet, and ChineseCaptchaServlet. All generate CAPTCHA image/answer pairs, but StickyCaptchaServlet and ChineseCaptchaServlet are “sticky” to the user’s session: page reloads will render the same CAPTCHA instead of generating a new one. An example mapping for StickyCaptchaServlet:

<servlet>
<servlet-name>StickyCaptcha</servlet-name>
<servlet-class>nl.captcha.servlet.StickyCaptchaServlet</servlet-class>
<init-param>
<param-name>width</param-name>
<param-value>250</param-value>
</init-param>
<init-param>
<param-name>height</param-name>
<param-value>75</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>StickyCaptcha</servlet-name>
<url-pattern>/stickyImg</url-pattern>
</servlet-mapping>


The width and height parameters are optional; if unprovided the image will default to 200×50.

4. Restart your webserver.
5. Browse to the location given by the url-pattern defined in web.xml, e.g., http://localhost:8080/stickyImg. If everything has been set up correctly you should see a CAPTCHA image.
6. Now create a JSP called captcha.jsp. Add the following code inside the <body> element:

<img src="/stickyImg" />
<form action="/captchaSubmit.jsp" method="post">
<input name="answer" />
</form>

7. Create another JSP called captchaSubmit.jsp. Add the following:

<%@ page import="nl.captcha.Captcha" %>
...
<% // We're doing this in a JSP here, but in your own app you'll want to put
// this logic in your MVC framework of choice.
Captcha captcha = (Captcha) session.getAttribute(Captcha.NAME);
request.setCharacterEncoding("UTF-8"); // Do this so we can capture non-Latin chars
String answer = request.getParameter("answer");
if (captcha.isCorrect(answer)) { %>
<b>Correct!</b>
<% } %>


8. Browse to /captcha.jsp. You should get your CAPTCHA image, as well as a form for entering your answer. Submit the form and see what happens.