Spring 4 Basic CAPTCHA Code Example

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

Within this page, the root folder of the extracted archive is referred as the <BDC-DIR>.

This example is in the <BDC-DIR>/examples/t_api-captcha-spring4-api_basics/ folder; and contains the following files:

Example files

Running Example

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.

basic.jsp

<%@page trimDirectiveWhitespaces="true"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@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:form action="validate" modelAttribute="basicExample" method="POST" cssClass="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:form>
</body>
</html>

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

BasicController.java

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

import com.captcha.botdetect.examples.springmvc.basic.model.BasicExample;
import com.captcha.botdetect.web.servlet.Captcha;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class BasicController {
  
  @RequestMapping(value = "/basic", method = RequestMethod.GET)
  public ModelAndView showForm() {
    return new ModelAndView("basic");
  }
  
  @RequestMapping(value = "/validate", method = RequestMethod.POST)
  public ModelAndView onSubmit(HttpServletRequest request, 
                @Valid @ModelAttribute("basicExample")BasicExample basicExample) 
  {
    // 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("basic", "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;
  }

}

The BasicExample model has no BotDetect Captcha related code except boilerplate elements.

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 xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
     http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">

  <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.css</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.Beta3.7 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.