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:



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):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="http://www.w3.org/1999/xhtml"

	<style type="text/css">
<h:form id="registration" prependId="false">

		<h:messages id="messages" />


			<td><h:outputLabel for="txtEmailId" value="Enter your Email ID*" />
				<h:inputText id="txtEmailId" required="true"
					value="#{registerBean.emailId}" label="Email Id"
					validatorMessage="Email Id is not Valid">

			<td><h:outputLabel for="txtNameId" value="Enter your Name*" />
				<h:inputText id="txtNameId" required="true"
					value="#{registerBean.name}" label="Name">

			<td><h:outputLabel for="txtPasswordId" value="Enter Password*" />
				<h:inputSecret id="txtPasswordId" required="true"
					value="#{registerBean.password}" label="Password">

			<td><h:outputLabel for="txtConfirmPasswordId"
					value="Enter Confirm Password*" /> <h:inputSecret
					id="txtConfirmPasswordId" required="true"
					value="#{registerBean.confirmPassword}" label="Confirm Password">

			<td><h:outputLabel for="txtMobileNo"
					value="Enter your Mobile No*" /> <h:inputText id="txtMobileNo"
					required="true" label="Mobile No" value="#{registerBean.mobileNo}"
					validatorMessage="Enter a valid Mobile number having 10 digits">
					<f:validateRegex pattern="\d{10}"></f:validateRegex>

			<td><h:outputLabel for="txtCaptchaId"
					value="Enter text shown in the Image*" /> <h:inputText
					id="txtCaptchaId" required="true"
					value="#{registerBean.captchaText}" label="Enter Captcha"
					placeholder="Enter Security Code" autocomplete="false">
					<f:validator validatorId="captchaValidator" />
			<td align="center"><h:graphicImage id="imgCaptchaId"
					value="captcha.jpg" /> <h:commandLink
					onclick="document.getElementById('imgCaptchaId').src = 'captcha.jpg?' + Math.random();  return false">
					<h:graphicImage library="images"
						value="#{facesContext.externalContext.requestContextPath}/../images/refresh.png" />

			<td align="center"><h:commandButton value="Submit"
					action="#{registerBean.createNewUser}" ajax="false">



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

package net.javaonline.user.registration.bean;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

public class RegisterBean implements Serializable {

	private static final long serialVersionUID = 1L;

	private String emailId;
	private String name;
	private String mobileNo;
	private String password;
	private String confirmPassword;
	private String captchaText;

	public String getEmailId() {
		return emailId;

	public void setEmailId(String emailId) {
		this.emailId = emailId;

	public String getName() {
		return name;

	public void setName(String name) {
		this.name = name;

	public String getMobileNo() {
		return mobileNo;

	public void setMobileNo(String mobileNo) {
		this.mobileNo = mobileNo;

	public String getPassword() {
		return password;

	public void setPassword(String password) {
		this.password = password;

	public String getConfirmPassword() {
		return confirmPassword;

	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;

	public String getCaptchaText() {
		return captchaText;

	public void setCaptchaText(String captchaText) {
		this.captchaText = captchaText;

	public String createNewUser() {

		if (getPassword().compareTo(getConfirmPassword()) != 0) {
							new FacesMessage(
									"Password and Confirm Password does not match ",
			return "failure";
		if (getEmailId().equals("guest@abc.com") && getPassword().equals("guest123"))
			return "success";
			return "failure";


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

package net.javaonline.captcha;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.servlet.http.*;
import javax.servlet.*;

import java.io.*;
import java.awt.*;
import net.javaonline.captcha.util.Util;

public class CaptchaServlet extends HttpServlet {

	public static final String FILE_TYPE = "jpeg";

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Max-Age", 0);

		String captchaStr = "";

		captchaStr = Util.generateCaptchaText(6);

		try {

			int width = 100;
			int height = 40;

			Color bg = new Color(0, 255, 255);
			Color fg = new Color(0, 100, 0);

			Font font = new Font("Arial", Font.BOLD, 20);
			BufferedImage cpimg = new BufferedImage(width, height,
			Graphics g = cpimg.createGraphics();

			g.fillRect(0, 0, width, height);
			g.drawString(captchaStr, 10, 25);

			HttpSession session = request.getSession(true);
			session.setAttribute("CAPTCHA", captchaStr);

			OutputStream outputStream = response.getOutputStream();

			ImageIO.write(cpimg, FILE_TYPE, outputStream);

		} catch (Exception e) {

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);


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

generateCaptchaText method:
package net.javaonline.captcha.util;

public class Util {

	public static String generateCaptchaText(int captchaLength) {

		String saltChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
		StringBuffer captchaStrBuffer = new StringBuffer();
		java.util.Random rnd = new java.util.Random();

		// build a random captchaLength chars salt
		while (captchaStrBuffer.length() < captchaLength) {
			int index = (int) (rnd.nextFloat() * saltChars.length());
			captchaStrBuffer.append(saltChars.substring(index, index + 1));

		return captchaStrBuffer.toString();



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

package net.javaonline.captcha;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.servlet.http.HttpServletRequest;

@FacesValidator(value = "captchaValidator")
public class CaptchaValidator implements Validator {

	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		String captchaEntered = (String) value;

		System.out.println("captcha " + captchaEntered);

		FacesMessage message = null;

		try {

			if (captchaEntered == null || captchaEntered.isEmpty())
				message = new FacesMessage(
						"Please Enter Security Code shown in the image box");

			else {
				HttpServletRequest request = (HttpServletRequest) FacesContext
				javax.servlet.http.HttpSession session = request.getSession();
				String captcha = (String) session.getAttribute("CAPTCHA");
				System.out.println("captcha G " + captcha);
				if (!captchaEntered.equals(captcha)) {
					message = new FacesMessage("Captcha is invalid");

			if (message != null)
				throw new ValidatorException(message);

		} catch (Exception ex) {
			throw new ValidatorException(new FacesMessage(ex.getMessage()));



Create JSF page for Acknowledgement for User creation

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns="http://www.w3.org/1999/xhtml"

	<title>JSF 2.2 Registration with Captcha</title>
<h:body bgcolor="white">

	<h2>You are registered with us successfully</h2>

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>JSF Captcha</display-name>
		<servlet-name>Faces Servlet</servlet-name>
		<servlet-name>Faces Servlet</servlet-name>


faces-config.xml for defining navigation-rule:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"





Run the project by calling the below 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