Añadir la protección de BotDetect CAPTCHA usando Java
Importante
Cómo este ejemplo usa la versión de componente COM de BotDetect CAPTCHA, servidores y máquinas de desarrollo deben utilizar Windows. Por el momento no podemos dar soporte para Java sobre otros sistemas operativos.
Requerimientos
- JDK 1.6.0_07 – http://java.sun.com
- Eclipse 3.4 IDE para desarrollar en Java EE – http://www.eclipse.org/downloads/
- Tomcat 6.0.14 – http://jakarta.apache.org/tomcat
- JACOB – Java COM Bridge – http://sourceforge.net/projects/jacob-project
- BotDetect 2.0 CAPTCHA – versión gratuita de prueba de BotDetect CAPTCHA
Otras versiones más nuevas de los productos deben funcionar correctamente.
Creando el proyecto web de Java
Seleccione "Dynamic Web Project" desde el menú "File\New\Project"
En el nombre del proyecto, "Project name", escriba "captchaWeb", luego seleccione "Apache Tomcat v6.0" en "Target Runtime" y finalmente presione "Finish".
En el diálogo a continuación, elija "Yes"
En el explorador del proyecto, vaya a "Java Resources: src", haga clic secundario en este elemento y luego elija "New\Package". En el campo para el nombre, señalado como "Name", escriba "org.lanapsoft.captcha" y presione "Finish".
Haga clic secundario sobre el nuevo paquete que ha creado. Desde las opciones elija "New\Class". Como nombre "Name" coloque "CaptchaServlet" y presione "Finish".
Pegue el siguiente código en la nueva clase:
package org.lanapsoft.captcha;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.SafeArray;
import com.jacob.com.Variant;
public class CaptchaServlet extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
ActiveXComponent activeXComponent = null;
String command = null;
String[] params = null;
String queryString = (String) request.getQueryString();
if (queryString != null) {
params = queryString.split("=");
command = params[0];
}
HttpSession session = request.getSession(true);
activeXComponent = (ActiveXComponent)
session.getAttribute("captchaComponent");
if (activeXComponent == null) {
activeXComponent = new ActiveXComponent("Lanap.BotDetect");
session.setAttribute("captchaComponent", activeXComponent);
}
if ("CreateImage".equals(command)) {
activeXComponent.setProperty("CodeLength", 5);
activeXComponent.setProperty("Format", "Jpeg");
activeXComponent.setProperty("ImageWidth", 300);
activeXComponent.setProperty("ImageHeight", 100);
Variant createImage = activeXComponent.invoke("CreateImage");
SafeArray createImageSafeArray = createImage.toSafeArray();
byte createImageByteArray[] = createImageSafeArray.toByteArray();
Variant generatedValue = activeXComponent.invoke("GetValue");
session.setAttribute("generatedValue", generatedValue);
Variant generatedHashValue =
activeXComponent.invoke("GetHashValue");
session.setAttribute("generatedHashValue", generatedHashValue);
ServletOutputStream servletOutputStream = response
.getOutputStream();
servletOutputStream.write(createImageByteArray);
servletOutputStream.flush();
servletOutputStream.close();
} else if ("CreateSound".equals(command)) {
Variant generatedValue =
(Variant)session.getAttribute("generatedValue");
Variant createSound =
activeXComponent.invoke("CreateSoundFromCode",
generatedValue);
SafeArray createImageSafeArray = createSound.toSafeArray();
byte createImageByteArray[] = createImageSafeArray.toByteArray();
ServletOutputStream servletOutputStream = response
.getOutputStream();
servletOutputStream.write(createImageByteArray);
servletOutputStream.flush();
servletOutputStream.close();
} else if ("userCode".equals(command)) {
String userCodeParam = params[1];
Variant userCode = new Variant();
userCode.putString(userCodeParam);
Variant generatedHashValue = (Variant)
session.getAttribute("generatedHashValue");
Variant validate = activeXComponent.invoke("Validate", userCode,
generatedHashValue);
boolean success = validate.getBoolean();
if (success) {
response.sendRedirect("/captchaWeb/success.htm");
} else {
response.sendRedirect("/captchaWeb/failure.htm");
}
}
}
}
Para resolver los errores de compilación, haga clic secundario sobre el proyecto y vaya a propiedades. Elija "Java Build Path" y coloque "Add Library...", para configurar la librería requerida
En la siguiente pantalla elija "User Library" y presione "Next".
Ahora en "User Libraries".
Ahora en "New".
Escriba "jacob" para nombre "User library name" y presione "OK".
Luego haga clic en "Add jars", vaya a la carpeta "Jacob" y añada "jacob.jar".
Haga clic en "OK", "Finish" y nuevamente "OK". Ahora no debería haber errores.
En el explorador del proyecto, vaya a "WebContent\WEB-INF", abra "web.xml" y cambie a la vista de código fuente con la pestaña "Source".
Pegue el siguiente código:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>captchaWeb</display-name>
<welcome-file-list>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>captchaWeb</servlet-name>
<servlet-class>org.lanapsoft.captcha.CaptchaServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>captchaWeb</servlet-name>
<url-pattern>/captcha/*</url-pattern>
</servlet-mapping>
</web-app>
Nuevamente en el explorador del proyecto, haga clic secundario sobre "WebContent" y luego seleccione "New\File". Escriba "index.htm" y presione "Finish".
Repita el mismo proceso para crear otros archivos llamados "success.htm" y "failure.htm".
Preque el siguiente código en cada uno de esos archivos:
index.htm
<html>
<body>
<form name="searchForm" method="get" action="/captchaWeb/captcha">
<table>
<tr>
<td>
<img src="/captchaWeb/captcha?CreateImage" />
</td>
</tr>
<tr>
<td>
<b>Sound:</b>
<a href="/captchaWeb/captcha?CreateSound">
<img src="speaker.gif" alt="Reproducir sonido" />
</a>
</td>
</tr>
<tr>
<td colspan="2" align="right">
<input type="text" name="userCode" />
</td>
</tr>
<tr>
<td colspan="2" align="right">
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
</body>
</html>
success.htm
<html> <h1>success</h1> </html>
failiure.htm
<html> <h1>failure</h1> </html>
Vaya ahora hacia "WebContent\WEB-INF\lib" en el explorador del proyecto y pegue el archivo "jacob-1.14.3-x86.dll".
Haga clic secundario sobre el proyecto "captchaWeb", seleccione "Properties", luego "Java EE Module Dependencies" y marque la casilla de la biblioteca "jacob". Presione "OK".
Vaya ahora al menú "Window\Show View" y luego seleccione "Servers". En "Servers", haga clic secundario sobre la rama principal y seleccione "New\Server".
Seleccione "Tomcat v6.0 Server" y luego presione "Next".
Sobre "Add and Remove Projects", seleccione "captchaWeb" luego presione "Add", y finalmente "Finish".
En "Servers", haga clic secundario sobre el servidor, seleccione "Start" para iniciarlo. Ahora vaya a "Run\Run Configurations", seleccione "Tomcat v6.0 Server at localhost" y desde la pestaña "Arguments", añada el siguiente argumento "-Djava.library.path=“location_of_your_workspace\ captchaWeb\WebContent\WEB-INF\lib". Presione "Apply" y "Close".
Reinicie el servidor, ahora abra su navegador web y escriba la siguiente URL http://localhost:8080/captchaWeb/index.htm.
Si usted escribe el código en pantalla será redireccionado hacia success.htm
De otra forma, se mostrará la página failure.htm
Configurando el entorno Java
Si usted no tiene Java EE Developer Tools instalado en Eclipse, vaya al menú "Help\Software Updates...". En la pestaña "Available Software" elija "Java EE Developer Tools" y haga clic en "Install".
En Eclipse, vaya a "Window\Preferences" y luego a "Java\Installed JREs" para comprobar la versión instalada del JRE.
Si no hay ningún JRE, haga clic en "Add..." y busque la carpeta correspondiente.
En "Server\Runtime Environments" haga clic en "Add..."
Seleccione "Apache Tomcat v6.0" y luego "Next".
Haga clic en "Browse" para indicarle al entorno donde tiene Tomcat instalado. Terminando, haga clic en "Finish" y luego en "OK".
Versiones Actuales de BotDetect
- BotDetect ASP.NET CAPTCHA v2.0.152009–11–23
- BotDetect ASP CAPTCHA v2.0.92009–02–12
Advertencia
Esta página es una traducción no oficial de la página original: How To Add BotDetect CAPTCHA Protection to Java Forms y puede estar incompleta, incorrecta o poco actualizada.
Última traducción del 2009-12-18. Esto se aplica para los productos BotDetect ASP.NET CAPTCHA v2.0.15 y BotDetect ASP CAPTCHA v2.0.9.































