In this article we will learn how to make CAPTCHA codes in JSP with a simple example.

What a CAPTCHA is


The acronym CAPTCHA stands for "Completely Automated Public Turing test to tell Computers and Humans Apart". Since the dawn of the internet, people have tried to abuse or hack websites for both sport and profit. As the abuse became profitable, the scale of abuse grew using automated software (sometimes referred to as robots or bots). To prevent bots from overrunning sites with spam, fraudulent registrations, fake entries and other notorious things, publishers responded by testing users to see if they were human or not.

In other words it is a type of challenge-response test used in computing to determine whether or not the user is human.

A CAPTCHA looks like:

Captcha

Now let's learn how to make it.

Create a new project in any IDE you have, here we are making it in NetBeans and we are creating only one JSP file in our project named CAPTCHA.

An overview of project creation.

Captcha.jsp
  1. <%@page contentType="text/html" pageEncoding="UTF-8"%>  
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  
  3. "http://www.w3.org/TR/html4/loose.dtd">   
  4. <html>  
  5. <head>  
  6.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7.     <title>JSP Page</title>  
  8. </head>  
  9. <body>  
  10. <%  
  11. StringBuffer sb=new StringBuffer();  
  12. for(int i=1;i<=5;i++)  
  13. {  
  14.     sb.append((char)(int)(Math.random()*79+23+7));  
  15. }  
  16. String cap=new String(sb);  
  17. %>  
  18. <div style="background-color: skyblue">  
  19. <center>  
  20. <h1>Captcha Demo</h1>  
  21. <script type ="text/javascript">  
  22. function validation(){  
  23.     var c = document.forms ["f1"]["cap1"].value;  
  24.     if(c==null||c=="")  
  25.     {  
  26.        alert ("Please Enter Captcha");  
  27.        return false;  
  28.     }  
  29. }  
  30. </script>  
  31. <form action="log" name="f1" onsubmit="return validation()">  
  32. <table border="0">  
  33.     <tbody>  
  34.        <tr>  
  35.         <td>  
  36.           <div style="background-color: aqua"><h2><s><i><font face="casteller"><%=cap%></font></i></s></h2></div>  
  37.         </td>  
  38.         <td><input type="text" name="cap1" value="" /></td>  
  39.         <td><input type="hidden" name="cap2" value='<%=cap%>' readonly="readonly" </td>  
  40.       </tr>  
  41.    </tbody>  
  42. </table>  
  43. <input type="submit" value="OK" />  
  44. <input type="reset" value="Reset" />  
  45. </form>  
  46.     </center>  
  47.     </div>  
  48. </body>  
  49. </html> 

Output

Outputs 

Next Recommended Readings