Spring 2 Basic CAPTCHA Code Example

First Time Here?

Check the BotDetect Spring Captcha Quickstart for key integration steps.

The Spring MVC 2 Basic Captcha code example shows the most basic source code required to protect a Spring MVC form with BotDetect CAPTCHA and validate the user input.

Download the BotDetect Java library and run this example

Example Location

The Spring MVC 2 Basic CAPTCHA code example is included in the
examples/simple-api/bdc4-simple-api-spring-mvc-2-basic-captcha-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, botdetect-jsp20.jar, and hsqldb.jar are in the classpath.

index.jsp

<%@page trimDirectiveWhitespaces="true"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="botDetect" uri="https://captcha.com/java/jsp/simple-api"%>
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>BotDetect Java CAPTCHA Validation: Spring MVC Basic Code Example</title>
  <link rel="stylesheet" href="stylesheet.css" type="text/css" />
</head>
<body>
  <form method="post" action="" class="column" id="form1">
    <h1>BotDetect Java CAPTCHA Validation: <br /> Spring MVC Basic Code Example</h1>
    <fieldset>
      <legend>Java CAPTCHA validation</legend>
      <label for="captchaCode">Retype the characters from the picture:</label>

      <!-- Adding BotDetect Captcha to the page -->
      <botDetect:simpleCaptcha id="basicExample"/>

      <div class="validationDiv">
        <input name="captchaCode" type="text" id="captchaCode" value="${basicExample.captchaCode}" />
        <input type="submit" name="validateCaptchaButton" value="Validate" id="validateCaptchaButton" />
        <span class="correct">${basicExample.captchaCorrect}</span>
        <span class="incorrect">${basicExample.captchaIncorrect}</span>
      </div>
    </fieldset>
  </form>
</body>
</html>

We add Captcha protection to the form using the standard procedure.

IndexController.java

package com.captcha.botdetect.examples.springmvc.basic.controller;

import com.captcha.botdetect.examples.springmvc.basic.model.BasicExample;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.captcha.botdetect.web.servlet.SimpleCaptcha;

public class IndexController extends SimpleFormController {

  public IndexController() {
    setCommandClass(BasicExample.class);
  }

  @Override
  protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response,
      Object command, BindException errors) {
    BasicExample basicExample = (BasicExample) command;
    
    // validate the Captcha to check we're not dealing with a bot
    SimpleCaptcha captcha = SimpleCaptcha.load(request, "basicExample");
    boolean isHuman = captcha.validate(basicExample.getCaptchaCode());
    if (isHuman) {
      basicExample.setCaptchaCorrect("Correct code");
      basicExample.setCaptchaIncorrect("");
    } else {
      basicExample.setCaptchaCorrect("");
      basicExample.setCaptchaIncorrect("Incorrect code");
    }
    
    basicExample.setCaptchaCode("");
    return new ModelAndView("index", "basicExample", basicExample);
  }
}

Controller's onSubmit method is pretty straightfoward. To keep it simple we just set appropriate messages upon Captcha validaton and then return to the original form.
In your application, you would of course perfom the form action you want to protect from bots after successful Captcha validation.

BasicExample.java

package com.captcha.botdetect.examples.springmvc.basic.model;

public class BasicExample {
  
  private String captchaCode, captchaCorrect, captchaIncorrect;

  public String getCaptchaCode() {
    return captchaCode;
  }

  public void setCaptchaCode(String userCaptchaCode) {
    this.captchaCode = userCaptchaCode;
  }

  public String getCaptchaCorrect() {
    return captchaCorrect;
  }

  public void setCaptchaCorrect(String captchaCorrect) {
    this.captchaCorrect = captchaCorrect;
  }

  public String getCaptchaIncorrect() {
    return captchaIncorrect;
  }

  public void setCaptchaIncorrect(String captchaIncorrect) {
    this.captchaIncorrect = captchaIncorrect;
  }

}

A Command object has no BotDetect Captcha related code except boilerplate elements.

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.5.xsd">

  <captchaStyles>
    <captchaStyle>
      <name>basicExample</name>
      <userInputID>captchaCode</userInputID>
      <codeLength>6</codeLength>
    </captchaStyle>
  </captchaStyles>

</botdetect>

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

web.xml

Note: Here is how to register BotDetect servlet in case you are using Spring Boot.

<?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>
  
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.htm</url-pattern>
  </servlet-mapping>
  
  <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>redirect.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.5 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.