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 object properties in Java form source.

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 (CaptchaId values sent to the Captcha 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.

Shared Captcha settings should always be placed in the WEB-INF/web.xml file, and only diverging settings set through Captcha object instance properties in form code, to avoid code duplication.

Settings that affect only Captcha container markup generation take effect immediately (changing captcha.getHtml(pageContext.getServletContext()) output), but settings that affect Captcha challenge (image or sound) generation in separate Http requests need to be saved in Java Session state when set through Captcha object instance properties in form source, consuming server resources and reverting to defaults when the Java Session expires.

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/bdc4-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 and botdetect-servlet.jar are in the classpath.

index.jsp

<%@page import="com.captcha.botdetect.web.CaptchaUrls"%>
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@page import="com.captcha.botdetect.HelpLinkMode"%>
<%@page import="com.captcha.botdetect.SoundRegenerationMode"%>
<%@page import="com.captcha.botdetect.SoundFormat"%>
<%@page import="com.captcha.botdetect.SoundStyle"%>
<%@page import="com.captcha.botdetect.ImageFormat"%>
<%@page import="com.captcha.botdetect.ImageSize"%>
<%@page import="com.captcha.botdetect.ImageStyle"%>
<%@page import="com.captcha.botdetect.CodeStyle"%>
<%@page import="com.captcha.botdetect.web.servlet.Captcha"%>
<%@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="<%= pageContext.getServletContext().getContextPath() + CaptchaUrls.getLayoutStyleSheetUrl() %>" />
  <link type="text/css" rel="stylesheet" href="stylesheet.css" />
  <script src="<%= pageContext.getServletContext().getContextPath() + CaptchaUrls.getScriptIncludeUrl()%>"></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
        Captcha captcha1 = Captcha.load(request, "captcha1");
        captcha1.setUserInputID("captchaCode1");
        
        captcha1.setCodeLength(6);
        captcha1.setCodeStyle(CodeStyle.NUMERIC);
        captcha1.setCodeTimeout(300); // 5 minutes
        captcha1.setDisallowedCodeSubstringsCsv("1,2,3,4,5,00,777,9999");

        captcha1.setImageStyle(ImageStyle.SUN_AND_WARM_AIR);
        captcha1.setImageSize(new ImageSize(250, 60));
        captcha1.setImageFormat(ImageFormat.PNG);

        captcha1.setSoundEnabled(true);
        captcha1.setSoundStyle(SoundStyle.SYNTH);
        captcha1.setSoundFormat(SoundFormat.WAV_PCM_8BIT_8KHZ_MONO);
        captcha1.setSoundRegenerationMode(SoundRegenerationMode.LIMITED);
        captcha1.setSoundStartDelay(100); // 0.1 seconds

        captcha1.setLocale("es-MX");
        captcha1.setImageTooltip("Custom Mexican Spanish Captcha image tooltip");
        captcha1.setSoundTooltip("Custom Mexican Spanish Captcha sound icon tooltip");
        captcha1.setReloadTooltip("Custom Mexican Spanish Captcha reload icon tooltip");
        captcha1.setHelpLinkUrl("custom-mexican-spanish-captcha-help-page.html");
        captcha1.setHelpLinkText("Custom Mexican Spanish Captcha help link text");

        captcha1.setReloadEnabled(true);
        captcha1.setUseSmallIcons(false);
        captcha1.setUseHorizontalIcons(false);
        captcha1.setSoundIconUrl("");
        captcha1.setReloadIconUrl("");
        captcha1.setIconsDivWidth(27);
        captcha1.setHelpLinkEnabled(true);
        captcha1.setHelpLinkMode(HelpLinkMode.TEXT);
        captcha1.setTabIndex(-1);
        captcha1.setAdditionalCssClasses("class1 class2 class3");
        captcha1.setAdditionalInlineCss("border: 4px solid #fff; background-color:#f8f8f8;");

        captcha1.setAddCssInclude(false);
        captcha1.setAddScriptInclude(false);
        captcha1.setAddInitScript(true);
        captcha1.setAutoUppercaseInput(true);
        captcha1.setAutoFocusInput(true);
        captcha1.setAutoClearInput(true);
        captcha1.setAutoReloadExpiredCaptchas(true);
        captcha1.setAutoReloadTimeout(7200); // 2 hours
        captcha1.setRemoteScriptEnabled(true);
        
        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
        Captcha captcha2 = Captcha.load(request, "captcha2");
        captcha2.setUserInputID("captchaCode2");

        captcha2.setCodeLength(3);
        captcha2.setCodeStyle(CodeStyle.ALPHA);
        captcha2.setCodeTimeout(900); // 5 minutes
        captcha2.setDisallowedCodeSubstringsCsv("AAA,BBB,CCC");
        
        List<ImageStyle> imageStyles = new ArrayList<ImageStyle>();
        imageStyles.add(ImageStyle.BLACK_OVERLAP);
        imageStyles.add(ImageStyle.GRAFFITI);
        imageStyles.add(ImageStyle.OVERLAP);
        
        captcha2.setImageStyle(imageStyles);
        captcha2.setImageSize(new ImageSize(120, 35));
        captcha2.setImageFormat(ImageFormat.PNG);
        
        captcha2.setCustomDarkColor(java.awt.Color.decode("#006400"));
        captcha2.setCustomLightColor(java.awt.Color.decode("#eeeeff"));
  
        captcha2.setSoundStyle(SoundStyle.DISPATCH);
        captcha2.setSoundFormat(SoundFormat.WAV_PCM_8BIT_8KHZ_MONO);
        captcha2.setSoundRegenerationMode(SoundRegenerationMode.NONE);

        captcha2.setLocale("fr-CA");
        captcha2.setImageTooltip("Custom Canadian French Captcha image tooltip");
        captcha2.setSoundTooltip("Custom Canadian French Captcha sound icon tooltip");
        captcha2.setReloadTooltip("Custom Canadian French Captcha reload icon tooltip");
        captcha2.setHelpLinkUrl("custom-canadian-french-captcha-help-page.html");
        captcha2.setHelpLinkText("Custom Canadian French Captcha help link text");

        captcha2.setReloadEnabled(true);
        captcha2.setUseSmallIcons(true);
        captcha2.setUseHorizontalIcons(true);
        captcha2.setSoundIconUrl("");
        captcha2.setReloadIconUrl("");
        captcha2.setIconsDivWidth(50);
        captcha2.setHelpLinkEnabled(true);
        captcha2.setHelpLinkMode(HelpLinkMode.IMAGE);
        captcha2.setTabIndex(15);
        captcha2.setAdditionalCssClasses("");
        captcha2.setAdditionalInlineCss("");
        
        captcha2.setAddCssInclude(false);
        captcha2.setAddScriptInclude(false);
        captcha2.setAddInitScript(true);
        captcha2.setAutoUppercaseInput(false);
        captcha2.setAutoFocusInput(false);
        captcha2.setAutoClearInput(false);
        captcha2.setAutoReloadExpiredCaptchas(true);
        captcha2.setAutoReloadTimeout(3600); // 1 hours
        captcha2.setSoundStartDelay(1000); // 1 second
        captcha2.setRemoteScriptEnabled(false);
        
        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 identifier unique to the page ("captcha1").

In the second one, we use a different Captcha identifier to distinguish between Captcha instances ("captcha2"). This is important to do when you add multiple Captcha protection to the form because Captcha codes and other Captcha data are stored in Session state using keys based on captcha id values.

If multiple Captcha instances in the form were using the same identifier, one Captcha's data would overwrite the other's when a visitor opened the form.

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.CaptchaServlet</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 CaptchaServlet used for BotDetect Captcha requests.


Please Note

BotDetect Java Captcha Library v4.0.Beta1 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.