JavaServer Pages CAPTCHA Tag Code Example

First Time Here?

Check the BotDetect JSP Captcha Quickstart for key integration steps.

The JSP Captcha Tag code example shows the most basic source code required to protect a JavaServer Pages form with BotDetect CAPTCHA's custom tag and validate the user input.

It can be used as a starting point when you are first learning how to use BotDetect.

Download the BotDetect Java library and run this example

Downloaded Location

The JSP Captcha Tag code example is included in the
examples/bdc4-jsp-captcha-tag-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 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: JSP CAPTCHA Tag Code Example</title>
  <link rel="stylesheet" href="stylesheet.css" type="text/css" />
</head>
<body>
  <form method="post" action="captchaTagAction" class="column" id="form1">
    <h1>BotDetect Java CAPTCHA Validation: <br /> JSP CAPTCHA Tag 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="exampleCaptchaTag" userInputID="captchaCode" />

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

Upon form submission CAPTCHA validation is performed in CaptchaActionTag servlet and result is forwarded back to the initial form.

CaptchaTagAction.java

package com.captcha.botdetect.examples.jsp.tag;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

public class CaptchaTagAction extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    Map<String, String> messages = new HashMap<String, String>();
    request.setAttribute("messages", messages);

    // validate the Captcha to check we're not dealing with a bot
    Captcha captcha = Captcha.load(request, "exampleCaptchaTag");
    boolean isHuman = captcha.validate(request.getParameter("captchaCode"));
    if (!isHuman) {
      // Captcha validation failed, show error message
      messages.put("captchaIncorrect", "Incorrect code");
    } else {
      // Captcha validation passed, perform protected action
      messages.put("captchaCorrect", "Correct code");
    }

    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
    dispatcher.forward(request, response);
  }
}

To perform CAPTCHA validation we have to initialize Captcha object with the same id as was used on the submitted form, and validate user input from corresponding user input client.The validation result is then forwarded to the form for display.

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>
  
  <servlet>
    <servlet-name>CaptchaTagAction</servlet-name>
    <servlet-class>com.captcha.botdetect.examples.jsp.tag.CaptchaTagAction</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CaptchaTagAction</servlet-name>
    <url-pattern>/captchaTagAction</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 and register CaptchaTagAction servlet used for validating captcha code.


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.