Choose Your Language

Thursday 8 October 2015

Generate and Validate Captcha Using JSP

Project Structure


index.jsp


<%--
    Document   : index
    Created on : Oct 9, 2015, 10:39:53 AM
    Author     : Aravind Sankaran Nair
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page import="nl.captcha.Captcha"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <center>
            <form action="/CaptchaExample/validatecaptcha.jsp" method="get">
            <img id="captcha" src="<c:url value="simpleCaptcha.jpg"/>" width="150"/>
            <input type="text" name="securitycode"/>
            <input type="submit" name="submit" value="validate captcha" id="submit" />
            </form>      
        </center>
    </body>
</html>

validatecaptcha.jsp

<%-- 
    Document   : validatecaptcha
    Created on : Oct 9, 2015, 10:54:33 AM
    Author     : Aravind Sankaran Nair
--%>

<%@ page import="nl.captcha.Captcha"%>
<%
Captcha captcha=(Captcha)session.getAttribute(Captcha.NAME);
String securitycode = request.getParameter("securitycode");
if (captcha.isCorrect(securitycode)) {
    %>
    <center><font color="red">Security code matching</font></center>
    <%}else {%>
    <center><font color="red">Security Code Mismatch</font></center>
    <%}%>

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>SimpleCaptchaServlet</servlet-name>
        <servlet-class>nl.captcha.servlet.SimpleCaptchaServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SimpleCaptchaServlet</servlet-name>
        <url-pattern>/simpleCaptcha.jpg</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Needed JAR Files

imaging.jar
jstl-1.2.jar
simplecaptcha-1.1.1.jar
standard.jar

No comments:

Post a Comment