How to Create A Simple Captcha Using Java Servlet

On this article im going to create a simple image captcha that will show a 5-random alphanumeric letters, im using SimpleCaptha library to help me creating images and validating user’s input.

First is a simple java servlet, it will build random images and store its value on httpsession.

package com.edw.captcha;

import java.awt.Color;
import java.awt.Font;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nl.captcha.Captcha;
import nl.captcha.backgrounds.GradiatedBackgroundProducer;
import nl.captcha.servlet.CaptchaServletUtil;
import nl.captcha.text.renderer.DefaultWordRenderer;

public class EdwCaptcha extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<Color> colors = new ArrayList<Color> ();
        List<Font> fonts = new ArrayList<Font>();
        fonts.add(new Font("Arial", Font.ITALIC, 40));
        Captcha captcha = new Captcha.Builder(120, 50)
                .addText(new DefaultWordRenderer(colors, fonts))
                .addBackground(new GradiatedBackgroundProducer(Color.white, Color.white))

        // display the image produced
        CaptchaServletUtil.writeImage(response, captcha.getImage());

        // save the captcha value on session
        request.getSession().setAttribute("simpleCaptcha", captcha); 

And now im registering my servlet on my web.xml,

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="" xmlns:xsi="" xsi:schemaLocation="">

Here is the result image generated from my servlet,

You can validate the submitted captcha values by comparing it with the values that you store in httpsession.




about 1 year ago

Thanks! It works perfectly. Easy to verify if typed code matches to image.



about 1 year ago

hi Tadeu, glad it can help

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked

:-[ (B) (^) (P) (@) (O) (D) :-S ;-( (C) (&) :-$ (E) (~) (K) (I) (L) (8) :-O (T) (G) (F) :-( (H) :-) (*) :-D (N) (Y) :-P (U) (W) ;-)