Create Captcha in JSP-Servlet

This project will demonstrate how to Create Captcha in JSP Servlet

  • LearnJSPServletWithRealApps
    • Java Resources
      • src/main/java
        • com.demo.servlets
          • AccountServlet.java
        • com.demo.helpers
          • CaptchaHelper.java
    • src
      • main
        • webapp
          • account
            • index.jsp
            • success.jsp
          • WEB-INF
            • web.xml
          • index.jsp
    • pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>LearnJSPServletWithRealApps</groupId>
    <artifactId>LearnJSPServletWithRealApps</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>Learn JSP-Servlet with Real Apps</name>
    <url>http://maven.apache.org</url>
    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>javax.servlet.jsp.jstl-api</artifactId>
            <version>1.2.1</version>
        </dependency>

        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>
    <build>
        <finalName>LearnJSPServletWithRealApps</finalName>
    </build>
</project>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isELIgnored="false"%>
<jsp:forward page="account"></jsp:forward>
package com.demo.helpers;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;

@WebServlet("/captcha-image")
public class CaptchaHelper extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("image/jpg");
        int iTotalChars = 6;
        int iHeight = 40;
        int iWidth = 150;
        Font font = new Font("Arial", Font.BOLD, 30);
        Random random = new Random();
        String sImageCode = (Long.toString(Math.abs(random.nextLong()), 36)).substring(0, iTotalChars);
        BufferedImage bufferedImage = new BufferedImage(iWidth, iHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2d = (Graphics2D) bufferedImage.getGraphics();
        int iCircle = 15;
        for (int i = 0; i < iCircle; i++) {
            graphics2d.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
        }
        graphics2d.setFont(font);
        for (int i = 0; i < iTotalChars; i++) {
            graphics2d.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
            if (i % 2 == 0) {
                graphics2d.drawString(sImageCode.substring(i, i + 1), 25 * i, 24);
            } else {
                graphics2d.drawString(sImageCode.substring(i, i + 1), 25 * i, 35);
            }
        }
        OutputStream outputStream = response.getOutputStream();
        ImageIO.write(bufferedImage, "jpeg", outputStream);
        graphics2d.dispose();
        HttpSession session = request.getSession();
        session.setAttribute("captcha_security", sImageCode);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

}
package com.demo.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/account")
public class AccountServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public AccountServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("account/index.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        String captcha = session.getAttribute("captcha_security").toString();
        String verifyCaptcha = request.getParameter("captcha");
        if (captcha.equals(verifyCaptcha)) {
            request.setAttribute("username", request.getParameter("username"));
            request.setAttribute("password", request.getParameter("password"));
            request.getRequestDispatcher("account/success.jsp").forward(request, response);
        } else {
            request.setAttribute("error", "Captcha Invalid");
            request.getRequestDispatcher("account/index.jsp").forward(request, response);
        }
    }

}
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isELIgnored="false"%>
<html>
<head>
<title>Register</title>
</head>
<body>

    <h3>Register Form</h3>
    <form method="post" action="${pageContext.request.contextPath }/account">
        <table border="0" cellpadding="2" cellspacing="2">
            <tr>
                <td>Username</td>
                <td><input type="text" name="username"/></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" name="password"/></td>
            </tr>
            <tr>
                <td>Captcha</td>
                <td>
                    <img src="captcha-image"/>
                    <br/>
                    <input type="text" name="captcha"/>
                    <br/>
                    ${error }
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="submit" value="Save"></td>
            </tr>
        </table>
    </form>

</body>
</html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isELIgnored="false" %>
<html>
<head>
<title>Success</title>
</head>
<body>

    <h3>Success Page</h3>
    Username: ${username }
    <br>
    Password: ${password }

</body>
</html>

Screenshots