How To Add BotDetect CAPTCHA Protection to JSP Forms

Protecting your JSP forms with BotDetect Java Captcha requires a few steps, outlined on this page. Displaying the Captcha challenge can be as simple as:

<%
Captcha captcha = Captcha.load(request, "exampleCaptcha");
captcha.renderCaptchaMarkup(
    pageContext.getServletContext(), pageContext.getOut());
%>
<input id="captchaCodeTextBox" type="text" name="captchaCodeTextBox" />

and checking user input when the form is submitted:

boolean isHuman = captcha.validate(request, 
    request.getParameter("captchaCodeTextBox"));

First Time Here?

Check the BotDetect JSP Captcha Quickstart for key integration steps.

You can also see how BotDetect Captcha protection has been added to various kinds of JSP forms and projects by running the BotDetect Captcha JSP integration code examples coming with the BotDetect installation. You can also reuse the code example source code that fits your requirements.

CAPTCHA Integration Steps

To add BotDetect Captcha protection to a JSP application:

Include BotDetect Library in the Classpath

BotDetect Captcha can simply be included in classpath by copying botdetect.jar from the BotDetect Java download package.

To protect specific application with BotDetect Captcha copy botdetect.jar into WEB-INF/lib directory of your application.

Copy botdetect.jar into lib directory of your web container or application server's domain in order to share BotDetect Captcha among multiple applications.

Register CaptchaServlet

Update your application configuration (web.xml) file.

<servlet-name>BotDetect Captcha</servlet-name>
    <servlet-class>botdetect.web.http.CaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>BotDetect Captcha</servlet-name>
    <url-pattern>/botdetectcaptcha</url-pattern>
</servlet-mapping>  

Display Captcha Protection on the JSP Form

We'll assume you already have a form which can be posted (<form method="post" ...), with other fields in place.

There are two ways to include Captcha protection on the JSP form:

JSP Scriptlet

This approach is especially useful when <form> tag has no action attribute since Captcha object will already be instantiated for validation.

First, on the top of the JSP form source file add:

<%@page import="botdetect.web.Captcha"%>

To display the Captcha test on your form, you will need the following Html elements:

  • A textbox for the Captcha code user input, with a label displaying Captcha instructions
  • The Captcha markup including the image, sound and reload icons etc., which will be generated by the Captcha library

For example:

<label for="captchaCode" class="prompt">
    Retype the code from the picture:</label>
<%
Captcha captcha = Captcha.load(request, "exampleCaptcha");
captcha.setUserInputClientId("captchaCode");
captcha.renderCaptchaMarkup(
    pageContext.getServletContext(), pageContext.getOut());
%>
<input id="captchaCode" type="text" name="captchaCode" />

The JSP scriptlet above creates a new instance of the Captcha class defined by the BotDetect Java Captcha library, tells it which textbox is used to input Captcha codes (default is captchaCodeTextBox), and calls the renderCaptchaMarkup(ServletContext ctx, Writer out) function to generate all needed BotDetect Html elements.

BotDetect captcha Tag

BotDetect custom captcha tag is designed to add CAPTCHA protection to JSP form as simple as possible.

At the top of the file put BotDetect taglib declaration:

<%@taglib prefix="botDetect" uri="botDetect"%>

Boilerplate Html elements are the same as in previous example, but JSP scriptlet is replaced with custom tag:

<label for="captchaCodeTextBox" class="prompt">
    Retype the code from the picture:</label>
<botDetect:captcha id="exampleCaptchaTag" userInputClientId="captchaCode"/>
<input id="captchaCode" type="text" name="captchaCode" />

When you open your form in a browser, the above declarations should render as:

BotDetect CAPTCHA added to an JSP page

If you are adding Captcha protection to multiple JSP forms in the same website, you should initialize each Captcha object with unique name (e.g. "registrationCaptcha", "commentCaptcha", ...).

Validate Captcha User Input During JSP Form Submission

Since we want to ensure only real human users can perform a certain action (e.g. account registration or comment submission), we also have to add Captcha validation code which will process form submissions, and only allow certain actions if Captcha validation succeeds.

Form Has No Action

In the simplest case (when the form posts to itself, i.e. the action attribute is not set), you will process form submissions on the form itself:

<%
if("POST".equalsIgnoreCase(request.getMethod())){
    boolean isHuman = captcha.validate(request, 
      request.getParameter("captchaCode"));
    if (isHuman) {
      // TODO: Captcha validation passed, perform protected action
    } else {
      // TODO: Captcha validation failed, show error message
    }
}
%>

The above code is very simple:

  • The if("POST".equalsIgnoreCase(request.getMethod())){ line ensures the code only runs when the form is submitted and if(request.getParameter("validate") != null){ line ensures that form is submitted via Validate button.
  • The boolean isHuman = captcha.validate(request, request.getParameter("captchaCode")); line calls the validate(HttpServletRequest request, String userCode) function of the Captcha object, which returns true if the submitted Captcha code matches the one used for Captcha image generation, or false otherwise.

This approach is shown in the BotDetect basic JSP integration code example included in the BotDetect download package.

Separate Servlet Processing Action

If your form posts to a separate servlet, you can use the same Captcha validation code. You just have to create Captcha object instance with the same name as the one used on the form first:

Captcha captcha = Captcha.load(request, "exampleCaptcha");
// validate the Captcha to check we're not dealing with a bot
boolean isHuman = captcha.validate(request,
    request.getParameter("captchaCode"));
if (isHuman) {
  // TODO: Captcha validation passed, perform protected action
} else {
  // TODO: Captcha validation failed, show error message
}

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

In this trivial case response is redirected back to original form.

This approach is shown in the BotDetect JSP Captcha Tag integration code example included in the BotDetect download package.


Please Note

BotDetect Java Captcha Library v4.0.Beta3 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.