Captcha validation in Java web applications
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:
<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>/Captcha.png</url-pattern> </servlet-mapping>
Suppose now, that we want to use captcha in a registration form and we process user input in a servlet – SimpleCaptchaServlet- .The registration form could be:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Simple Captcha</title> </head> <body> <form action="SimpleCaptchaServlet"> 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" /> </form> </body> </html>
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 java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nl.captcha.*;
public class SimpleCaptchaServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public SimpleCaptchaTestServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
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
if (!captcha.isCorrect(captchaAnswer)) {
// further process goes here
}
}
}
