JavaServer Pages Form CAPTCHA Code Example

The JSP Form Captcha code example shows how to add BotDetect CAPTCHA protection to a typical JSP form.

First Time Here?

Check the BotDetect JSP Captcha Quickstart for key integration steps.

Captcha validation is integrated with other form fields validation, and only submissions that meet all validation criteria are accepted.

If the Captcha is successfully solved but other field validation fails, the Captcha is hidden since the users have already proven they are human.

This kind of validation could be used on various types of public forms which accept messages, and are at risk of unwanted automated submissions.

For example, it could be used to ensure bots can't submit anything to a contact form, add guestbook entries, blog post comments or anonymous message board / forum replies.

Downloaded Location

The JSP Form CAPTCHA Example is included in examples folder of the download package as bdc3-jsp-form-captcha-example.war file. Deploying (unpacking) the file will create a standard JSP directory tree.

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="botDetect" uri="botDetect"%>
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>BotDetect CAPTCHA Form Example</title>
    <link rel="stylesheet" href="stylesheet.css" type="text/css"/>
  </head>
  <body>
    <form action="captchaFormAction" method="post">
      <h1>BotDetect CAPTCHA Form Example</h1>
      <fieldset>
        <legend>CAPTCHA included in JSP form validation</legend>
        <div class="input">
          <label for="name">Name:</label>
          <input type="text" name="name" class="textbox" 
              value="${param.name}" /><br>
          <span class="incorrect">${messages.nameIncorrect}</span>
        </div>
        <div class="input">
          <label for="email">Email:</label>
          <input type="text" name="email" class="textbox" 
              value="${param.email}" /><br>
          <span class="incorrect">${messages.emailIncorrect}</span>
        </div>
        <div class="input" >
          <label for="message">Short message:</label>
          <textarea class="inputbox" name="message" rows="5" cols="40" >
              ${param.message}</textarea><br>
          <span class="incorrect">${messages.messageIncorrect}</span>
        </div>
        <% if(request.getSession().getAttribute("isCaptchaValid") == null) { %>
          <label for="captchaCodeTextBox" class="prompt">
              Retype the code from the picture:</label>
          <!-- Adding BotDetect Captcha to the page -->
          <botDetect:captcha id="formCaptcha"
                     codeLength="3"
                     imageWidth="150"
                     imageStyle="graffiti, graffiti2"/>
          <div class="validationDiv">
            <input id="captchaCodeTextBox" type="text" 
                name="captchaCodeTextBox" /><br>
            <span class="incorrect">${messages.captchaCodeIncorrect}</span>
          </div>
        <% } %>
        <input type="submit" name="submit" value="Submit" />&nbsp;
        <span class="correct">${messages.captchaCodeCorrect}</span>
      </fieldset>
    </form>
  </body>
</html>

Beside the Captcha code input textbox, the example form contains three other fields, which are all validated the same way in form processing code.

To hide the Captcha challenge after the user solves it (regardless of other field validation status), the Captcha object's Html value is only added to the page if not already solved (if(request.getSession().getAttribute("isCaptchaValid") == null ...).

CaptchaFormAction.java

package botdetect.examples.jsp.form;

import botdetect.web.Captcha;
import java.io.IOException;
import java.util.Date;
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 javax.servlet.http.HttpSession;

public class CaptchaFormAction extends HttpServlet {
  HttpSession session;
  
  @Override
  protected void doPost(HttpServletRequest request, 
      HttpServletResponse response)
      throws ServletException, IOException {

    Map<String, String> messages = new HashMap<String, String>();
    request.setAttribute("messages", messages);
    Captcha captcha = Captcha.load(request, "formCaptcha");
    boolean messageValid = true;
    String destinationPage = "/index.jsp";
    
    session = request.getSession(true);
    
    if(session.getAttribute("isCaptchaValid") == null){
      // validate the Captcha to check we're not dealing with a bot
      boolean isHuman = captcha.validate(request, 
          request.getParameter("captchaCodeTextBox"))
      if (isHuman) {
        // Captcha validation passed, perform protected action
        session.setAttribute("isCaptchaValid", true);
      } else {
        // Captcha validation failed, show error message
        messages.put("captchaCodeIncorrect", "*");
        messageValid = false;
      }
    }
  
    if(!isValidName(request.getParameter("name"))){
      messages.put("nameIncorrect", "*");
      messageValid = false;
    }
    
    if(!isValidEmail(request.getParameter("email"))){
      messages.put("emailIncorrect", "*");
      messageValid = false;
    }
    
    if(!isValidMessage(request.getParameter("message"))){
      messages.put("messageIncorrect", "*");
      messageValid = false;
    }
    
    if(messageValid){
      saveMessage(request.getParameter("name"), 
          request.getParameter("email"), request.getParameter("message"));
      session.removeAttribute("isCaptchaValid");
      destinationPage = "/messages.jsp";
    }
    
    
    RequestDispatcher dispatcher = 
        getServletContext().getRequestDispatcher(destinationPage);
    dispatcher.forward(request, response);
  }
  
  private boolean isValidName(String name){
    if(name == null){
      return false;
    }
    return name.length() > 2 && name.length() < 30;
  }
  
  private boolean isValidEmail(String email){
    if(email == null){
      return false;
    }
    return email.matches("^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$");
  }
  
  private boolean isValidMessage(String message){
    if(message == null){
      return false;
    }
    return message.length() > 2 && message.length() < 255;
  }
  
  private void saveMessage(String name, String email, String messageText){
    Date timeStamp = new Date();
    String message = name + " (" + email + ") says: " + messageText;
    session.setAttribute("Message_"+timeStamp.getTime(), message);
  }
}

Form submission validation is performed in this file, which checks all required fields and redirects the user back to the form if validation fails. We use simple querystring parameters to pass validation results and remembered field values back to the form page (since this example warrants simplicity over real-world validation best practices).

Captcha validation is treated similar to other fields validation, and will work as long as we initialize the Captcha object with the same id ("formCaptcha") and retreive user code from the same userInputClientId (we used default value "captchaCodeTextBox") we used on the form page to add the Captcha.

Once form validation succeeds, the submitted values are saved and the Captcha challenge is reset (session.removeAttribute("isCaptchaValid");). This means each individual message requires Captcha validation, which helps prevent attacks where a malicious user could solve the Captcha once and then automate further form posts within the same Session.

messages.jsp

<%@page import="java.util.Enumeration"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>BotDetect CAPTCHA Form Example</title>
    <link rel="stylesheet" href="stylesheet.css" type="text/css"/>
  </head>
  <body>
    <form action="messages.jsp" method="post">
      <h1>BotDetect CAPTCHA Form Example</h1>
      <h2>View Messages</h2>

      <%
      boolean hasMessages = false;
      if("POST".equalsIgnoreCase(request.getMethod())){
        if(request.getParameter("clear") != null){
          request.getSession().invalidate();
        } else {
          Enumeration attributes = request.getSession().getAttributeNames();
          while(attributes.hasMoreElements()){
            String attribute = (String)attributes.nextElement();
            if(attribute.startsWith("Message_")){
              out.println("<p class=\"message\">" + 
                  session.getAttribute(attribute) + "</p>");
              hasMessages = true;
            }
          }
        }
      }
      %>
      <% if(hasMessages) {%>
      <p class="navigation"><input type="submit" name="clear" 
          action="messages.jsp" value="Clear" /></p>
      <% } %>
      <p class="navigation"><a href="index.jsp">Add Message</a></p>
    </form>
  </body>
</html>

This page displays all successfully submitted messages, and the user is automatically redirected here after validation of all form fields (including Captcha) is passed.

To run this example, botdetect.jar must be in the classpath.

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.