JSF 2.2 Captcha example with refresh button

This tutorial explains how to implement captcha in JSF page. Jsf Primefaces has inbuilt support of recaptcha feature. Recaptcha can be implemented using <p:captcha/> tag.  In this tutorial, let us create our own captcha in java and implement in JSF page. Yo can also view my earlier tutorial how to implement captcha in Spring Mvc.

Let use take an example of creating user registration page that accepts captcha so that user creation through automated tool can be prevented

Technology used in this project:

JSF 2.2

Eclipse IDE

Apache Tomcat 7.0 or 8.0

Java 1.8

Jars required for  JSF:

javax.faces.jar

jstl-1.2.jar

Project Directory Structure:

jsf captcha

Now let us see the steps to implement captcha in registration page in JSF.

Brief Steps:

1. Create a Registration page with captcha. JSF tag to display captcha image is
2. Create managed bean for the registration page.
2. Write java code (CaptchaServlet.java) for generating captcha text and image, store text on session and return image as response outputstream.
3. Write captcha validator code (CaptchaValidator.java) to verify whether the captcha text entered by the user and stored in the session matches or not.
<f:validator validatorId=”captchaValidator” />– this registers a named validator class (i.e. CaptchaValidator) on the UIComponent (captchaText input) for captcha validation

Steps in Detail:

Step 1: Design a Registration page having the following fields/components. Add/ Remove field(s) as per your requirement.
1. Email Id* as user id
2. Name*
3. Password* & Confirm Password*
4. Mobile No*
5. Captcha text
6. Image tag to display captcha image.
7. refresh button to regenerate captcha

JSF code (registration.xhtml):

Step 2: Create g managed bean for the registration page.

RegisterBean.java

Step 3: Servet code to generate Captcha image and returns the image as response outputstream

CaptchaServlet.java:

Code to generate random Text (i.e. captcha text generation)

generateCaptchaText method:

Step 4: Write validator code to verify whether the user entered captcha text matches with captcha stored in the session.

CaptchaValidator.java:

Create JSF page for Acknowledgement for User creation

registration_ack.xhtml:

web.xml:

faces-config.xml for defining navigation-rule:

Run the project by calling the below URL

url

registration outputregistration output1

 

Submitting the above form, throws the error “Captcha is invalid”

registration output2

Clicking on the refresh button, regenerate the captcha.

registration output3

 

The registration is successfullwhen you enter email-id as guest@abc.com and password as guest123 and the captcha as generated in the image box (here Trzngr)

registration success

 

Leave a Reply

3 Comments on "JSF 2.2 Captcha example with refresh button"


Guest
LeoLux
1 year 1 month ago

Nice tutorial! Good job 🙂

Guest
nahal
1 year 6 months ago

hello I use it but image dosent show, what am I do?! pleaz help me