Captcha images are used to ensure that data are submitted by a human being and not by some kind of spam robot.In this tutorial we will see how to use SimpleCaptcha API for generating image and audio captcha security codes.

As a first step,we need to configure simpleCaptcha servlet in the web.xml:




Suppose now, that we want to use captcha in a registration form and we process user input in a servlet – SimpleCaptchaTestServlet- .The registration form could be:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<form action="SimpleCaptchaTestServlet">
Name:<input type="text" name="name"><br/>
Surname:<input type="text" name="surname"><br/>
Name:<input type="text" name="username"><br/>
Password:<input type="password" name="password"><br/>
Email:<input type="text" name="email"><br/>
<img src="/Captcha.png" />
<input type="text" name="captchaAnswer"/>
<input type="submit" value="Submit"/>

In order now to validate that the above form is submitted by a human and not a computer is to compare the code that user has entered with the generated security code that is stored as session attribute by SimpleCaptcha servlet.


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nl.captcha.*;

public class SimpleCaptchaTestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public SimpleCaptchaTestServlet() {
        // TODO Auto-generated constructor stub

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//get Captcha code from session
		Captcha captcha = (Captcha) request.getSession().getAttribute(Captcha.NAME);
//get security code submitted by user
		String captchaAnswer=request.getParameter("captchaAnswer");
//compare security codes 
			//further process goes here