BotDetect CAPTCHA Options: Form Object Settings Code Example

The Java Captcha options: Form Object Settings example shows how to configure Captcha challenges by setting Captcha options in WEB-INF/botdetect.xml configuration file.

First Time Here?

Check the BotDetect Developer Crash Course for key integration steps.

Multiple Java forms within the same Java website can be protected by BotDetect Captcha challenges: e.g. you could add Captcha controls in both your Contact form and Registration form source.

To function properly, separate Captcha challenges placed on each form should have different names (captchaStyleName values sent to the SimpleCaptcha object constructor, captcha1 and captcha2 in this example), and can use completely different Captcha settings.

Even multiple Captcha instances placed on the same form won't interfere with each other's validation and functionality. And if a user opens the same page in multiple browser tabs, each tab will independently validate the shown Captcha code.

Download the BotDetect Java CAPTCHA Library and run this example

Downloaded Location

The Java Captcha options: Form object settings code example is included in the examples/simple-api/bdc4-simple-api-captcha-form-object-settings-example.war file of the download package. Deploying (unpacking) the file will create a standard JSP directory tree.

Running Example

This example's war file (in BotDetect download package) already embeds all dependencies.

In case you are making this example from scratch in your IDE, you need to ensure botdetect.jar, botdetect-servlet.jar are in the classpath.

index.jsp

<%@page import="com.captcha.botdetect.web.SimpleCaptchaUrls"%>
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@page import="com.captcha.botdetect.web.servlet.SimpleCaptcha"%>
<%@page trimDirectiveWhitespaces="true"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>BotDetect Java CAPTCHA Options: Form Object Settings Code Example</title>
  <link type="text/css" rel="stylesheet" href="botdetectcaptcha?get=layout-stylesheet" />
  <link type="text/css" rel="stylesheet" href="stylesheet.css" />
  <script src="botdetectcaptcha?get=script-include"></script>
</head>
<body>
  <form method="post" action="" class="column" id="form1">
    <h1>BotDetect Java CAPTCHA Options: <br /> Form Object Settings Code Example</h1>

    <fieldset>
      <legend>Java CAPTCHA validation</legend>
      <label for="captchaCode1">Retype the characters from the picture:</label>

      <% 
        // Adding BotDetect Captcha to the page
        SimpleCaptcha captcha1 = SimpleCaptcha.load(request, "captcha1");
        String captchaHtml1 = captcha1.getHtml();
        out.write(captchaHtml1);
      %>

      <div class="validationDiv">
        <input name="captchaCode1" type="text" id="captchaCode1" />
        
        <% 
          // when the form is submitted
          if ("POST".equalsIgnoreCase(request.getMethod())) {
            // validate the Captcha to check we're not dealing with a bot
            boolean isHuman1 = captcha1.validate(request.getParameter("captchaCode1"));
            if (!isHuman1) {
              // Captcha validation failed, show error message
              out.print("<span class=\"incorrect\">Incorrect code</span>");
            } else {
              // Captcha validation passed, perform protected action
              out.print("<span class=\"correct\">Correct code</span>");
            }
          }
        %>
      </div>
    </fieldset>
      
    <fieldset>
      <legend>Java CAPTCHA validation</legend>
      <label for="captchaCode2">Retype the characters from the picture:</label>

      <% 
        // Adding BotDetect Captcha to the page
        SimpleCaptcha captcha2 = SimpleCaptcha.load(request, "captcha2");
        String captchaHtml2 = captcha2.getHtml();
        out.write(captchaHtml2);
      %>

      <div class="validationDiv">
        <input name="captchaCode2" type="text" id="captchaCode2" />
        
        <% 
          // when the form is submitted
          if ("POST".equalsIgnoreCase(request.getMethod())) {
            // validate the Captcha to check we're not dealing with a bot
            boolean isHuman2 = captcha2.validate(request.getParameter("captchaCode2"));
            if (!isHuman2) {
              // Captcha validation failed, show error message
              out.print("<span class=\"incorrect\">Incorrect code</span>");
            } else {
              // Captcha validation passed, perform protected action
              out.print("<span class=\"correct\">Correct code</span>");
            }
          }
        %>
      </div>
    </fieldset>
    
    <input type="submit" name="submitButton" id="submitButton" value="Submit Form" />
  </form>
</body>
</html>

In the first one, Captcha protection is added to the form using a Captcha style name unique to the page ("captcha1"). In the second one, we use a different Captcha style name to distinguish between Captcha instances ("captcha2").

botdetect.xml

<?xml version="1.0" encoding="UTF-8"?>
<botdetect xmlns="https://captcha.com/schema/java" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://captcha.com/schema/java 
      https://captcha.com/schema/java/botdetect-4.0.beta3.2.xsd">

  <captchaStyles>
    
    <captchaStyle>
      <name>captcha1</name>
      
      <userInputID>captchaCode1</userInputID>
      <codeLength>6</codeLength>
      <codeStyle>NUMERIC</codeStyle>
      <codeTimeout>300</codeTimeout> <!-- 5 minutes -->
      <disallowedCodeSubstrings>1,2,3,4,5,00,777,9999</disallowedCodeSubstrings>

      <imageStyle>SUN_AND_WARM_AIR</imageStyle>
      <imageWidth>250</imageWidth>
      <imageHeight>50</imageHeight>
      <imageFormat>PNG</imageFormat>

      <soundEnabled>true</soundEnabled>
      <soundStyle>SYNTH</soundStyle>
      <soundFormat>WAV_PCM_8BIT_8KHZ_MONO</soundFormat>
      <soundRegenerationMode>LIMITED</soundRegenerationMode>
      <soundStartDelay>100</soundStartDelay> <!-- 0.1 seconds -->

      <locale>es-MX</locale>
      <imageTooltip>Custom Mexican Spanish Captcha image tooltip</imageTooltip>
      <soundTooltip>Custom Mexican Spanish Captcha sound icon tooltip</soundTooltip>
      <reloadTooltip>Custom Mexican Spanish Captcha reload icon tooltip</reloadTooltip>
      <helpLinkUrl>custom-mexican-spanish-captcha-help-page.html</helpLinkUrl>
      <helpLinkText>Custom Mexican Spanish Captcha help link text</helpLinkText>

      <reloadEnabled>true</reloadEnabled>
      <useSmallIcons>false</useSmallIcons>
      <useHorizontalIcons>false</useHorizontalIcons>
      <soundIconUrl></soundIconUrl>
      <reloadIconUrl></reloadIconUrl>
      <iconsDivWidth></iconsDivWidth>
      <helpLinkEnabled>true</helpLinkEnabled>
      <helpLinkMode>TEXT</helpLinkMode>
      <tabIndex>-1</tabIndex>
      <additionalCssClasses>class1 class2 class3</additionalCssClasses>
      <additionalInlineCss>border: 4px solid #fff; background-color:#f8f8f8;</additionalInlineCss>

      <addCssInclude>false</addCssInclude>
      <addScriptInclude>false</addScriptInclude>
      <addInitScript>true</addInitScript>
      <autoUppercaseInput>true</autoUppercaseInput>
      <autoFocusInput>true</autoFocusInput>
      <autoClearInput>true</autoClearInput>
      <autoReloadExpiredCaptchas>true</autoReloadExpiredCaptchas>
      <autoReloadTimeout>7200</autoReloadTimeout> <!-- 2 hours -->
      <remoteScriptEnabled>true</remoteScriptEnabled>
    </captchaStyle>
    
    
    <captchaStyle>
      <name>captcha2</name>
      
      <userInputID>captchaCode2</userInputID>
      <codeLength>3</codeLength>
      <codeStyle>ALPHA</codeStyle>
      <codeTimeout>900</codeTimeout> <!-- 5 minutes -->
      <disallowedCodeSubstrings>AAA,BBB,CCC</disallowedCodeSubstrings>

      <imageStyle>BLACK_OVERLAP,GRAFFITI,OVERLAP</imageStyle>
      <imageWidth>120</imageWidth>
      <imageHeight>35</imageHeight>
      <imageFormat>PNG</imageFormat>

      <customDarkColor>#006400</customDarkColor>
      <customLightColor>#eeeeff</customLightColor>

      <soundStyle>DISPATCH</soundStyle>
      <soundFormat>WAV_PCM_8BIT_8KHZ_MONO</soundFormat>
      <soundRegenerationMode>NONE</soundRegenerationMode>

      <locale>fr-CA</locale>
      <imageTooltip>Custom Canadian French Captcha image tooltip</imageTooltip>
      <soundTooltip>Custom Canadian French Captcha sound icon tooltip</soundTooltip>
      <reloadTooltip>Custom Canadian French Captcha reload icon tooltip</reloadTooltip>
      <helpLinkUrl>custom-canadian-french-captcha-help-page.html</helpLinkUrl>
      <helpLinkText>Custom Canadian French Captcha help link text</helpLinkText>

      <reloadEnabled>true</reloadEnabled>
      <useSmallIcons>true</useSmallIcons>
      <useHorizontalIcons>true</useHorizontalIcons>
      <soundIconUrl></soundIconUrl>
      <reloadIconUrl></reloadIconUrl>
      <iconsDivWidth>50</iconsDivWidth>
      <helpLinkEnabled>true</helpLinkEnabled>
      <helpLinkMode>IMAGE</helpLinkMode>
      <tabIndex>15</tabIndex>
      <additionalCssClasses></additionalCssClasses>
      <additionalInlineCss></additionalInlineCss>

      <addCssInclude>false</addCssInclude>
      <addScriptInclude>false</addScriptInclude>
      <addInitScript>true</addInitScript>
      <autoUppercaseInput>false</autoUppercaseInput>
      <autoFocusInput>false</autoFocusInput>
      <autoClearInput>false</autoClearInput>
      <autoReloadExpiredCaptchas>true</autoReloadExpiredCaptchas>
      <autoReloadTimeout>3600</autoReloadTimeout> <!-- 1 hours -->
      <soundStartDelay>1000</soundStartDelay> <!-- 1 second -->
      <remoteScriptEnabled>false</remoteScriptEnabled>
    </captchaStyle>
    
  </captchaStyles>

</botdetect>

In WEB-INF/botdetect.xml, we configure captcha options for the captcha1 and captcha2 captcha style names. You can find a full list of available Captcha configuration options and related instructions at the Captcha configuration options page.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    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_2_5.xsd">
  <session-config>
    <session-timeout>
      30
    </session-timeout>
  </session-config>
  
  <servlet>
    <servlet-name>BotDetect Captcha</servlet-name>
    <servlet-class>com.captcha.botdetect.web.servlet.SimpleCaptchaServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>BotDetect Captcha</servlet-name>
    <url-pattern>/botdetectcaptcha</url-pattern>
  </servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
In WEB-INF/web.xml file we register SimpleCaptchaServlet used for BotDetect Captcha requests.


Please Note

BotDetect Java Captcha Library v4.0.Beta3.2 is an in-progress port of BotDetect 4 Captcha, and we need you to guide our efforts towards a polished product. Please let us know if you encounter any bugs, implementation issues, or a usage scenario you would like to discuss.

Current BotDetect Versions