Spring MVC Basic CAPTCHA Code Example

First Time Here?

Check the BotDetect JSP Captcha Quickstart for key integration steps.

The Spring MVC 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.

This example is very similar to JSP Basic Captcha Example in terms of implementing BotDetect Captcha protection to form(s).

Download the BotDetect Java library and run this example

Downloaded Location

The Spring MVC Basic CAPTCHA code example is included in the
examples/bdc4-spring-mvc-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, and botdetect-jsp20.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"%>
<!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:captcha id="basicExample" userInputID="captchaCode" />

      <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.Captcha;

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
    Captcha captcha = Captcha.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.

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>
  
  <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.CaptchaServlet</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 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.