SimpleCaptcha is really nice and easy to use.
Here's an example how to use SimpleCaptcha with JSF 2.0 (the homepage has an example for JSP)
Note that I'm not even bothering to store the captcha value in the bean, I'm only validating it.
The bean:
// imports missing here
@ManagedBean
@SessionScoped
public class LoginBean implements Serializable
{
public void validateCaptcha(FacesContext context,
UIComponent componentToValidate,
Object value)
throws ValidatorException
{
HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
Captcha secretcaptcha = (Captcha) session.getAttribute(Captcha.NAME);
if (secretcaptcha.isCorrect(value.toString()))
return;
// optional: clear field
((HtmlInputText) componentToValidate).setSubmittedValue("");
throw new ValidatorException(new FacesMessage("Captcha does not match"));
}
}
The relevant segment of the facelet:
<h:form id="CaptchaForm">
Type this: <br/>
<h:graphicImage id="CaptchaImgID" value="/simpleCaptcha.png"/> <br/>
<h:inputText id="CaptchaID"
required="true"
requiredMessage="Captcha missing"
validator="#{loginBean.validateCaptcha}"
validatorMessage="Captcha does not match"
immediate="true">
</h:inputText>
<br/>
<h:commandButton value="Check"/>
<p/>
<!-- message for the input field -->
<h:message id="CaptchaMsgID" for="CaptchaID" style="color:red" />
</h:form>
The relevant segment of the web.xml:
<servlet>
<servlet-name>SimpleCaptcha</servlet-name>
<servlet-class>nl.captcha.servlet.SimpleCaptchaServlet</servlet-class>
<init-param>
<param-name>captcha-width</param-name>
<param-value>250</param-value>
</init-param>
<init-param>
<param-name>captcha-height</param-name>
<param-value>75</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SimpleCaptcha</servlet-name>
<url-pattern>/simpleCaptcha.png</url-pattern>
</servlet-mapping>
Enjoy :-)