Exemple d'intégration Wicket + Kaptcha
Kaptcha est une bibliothèque Java simple et facile à utiliser pour produire une validation d'image captcha. Dans ce tutoriel, nous vous montrons commentintegrate Kaptcha with Wicket framework, via Spring.
Bibliothèques utilisées:
-
Kaptcha v2.3.2
-
Wicket v1.4.17
-
portillon-ressort v1.4.17
-
Spring v3.0.5.RELEASE
Note
Cet article décrit principalement comment intégrer Kaptcha avec le framework Wicket, pour Wicket + Spring, veuillez vous référer à ce «Wicket + Spring
integration example».
1. Obtenez Kaptcha
D'après cethread, le propriétaire n'aime pas Maven, vous devez donc installer manuellement la bibliothèque dans votre référentiel Maven local.
1. Récupérez la bibliothèque Kaptcha icihttp://code.google.com/p/kaptcha/
2. Émettez sous la commande Maven pour l'installer manuellement.
mvn install:install-file -Dfile=c:\kaptcha-2.3.2.jar -DgroupId=com.google.code -DartifactId=kaptcha -Dversion=2.3.2 -Dpackaging=jar
3. Plus tard, vous pouvez inclure kaptcha dans votre fichier pom.xml.
Fichier: pom.xml
com.google.code kaptcha 2.3.2
2. DefaultKaptcha via Spring
Créez un bean Spring pour «DefaultKaptcha», nommécaptchaProducer.
Fichier: applicationContext.xml
3. CaptchaImage
Créez une classe CaptchaImage qui étend lesNonCachingImage
de Wicket et en utilisant la classeDynamicImageResource
pour générer dynamiquement l'image captcha.
Fichier: CaptchaImage.java
package com.example.user; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import javax.servlet.http.HttpServletRequest; import org.apache.wicket.Request; import org.apache.wicket.RequestCycle; import org.apache.wicket.markup.html.image.NonCachingImage; import org.apache.wicket.markup.html.image.resource.DynamicImageResource; import org.apache.wicket.protocol.http.WebRequest; import org.apache.wicket.spring.injection.annot.SpringBean; import com.google.code.kaptcha.Constants; import com.google.code.kaptcha.impl.DefaultKaptcha; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; public class CaptchaImage extends NonCachingImage { private static final String CAPTCHA_PRODUCER = "captchaProducer"; // inject via Spring @SpringBean private DefaultKaptcha captchaProducer; // private DefaultKaptcha captchaProducer; public CaptchaImage(String id) { super(id); setImageResource(new DynamicImageResource() { public byte[] getImageData() { ByteArrayOutputStream os = new ByteArrayOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os); try { BufferedImage bi = getImageCaptchaService(); encoder.encode(bi); return os.toByteArray(); } catch (Exception e) { throw new RuntimeException(e); } }; private BufferedImage getImageCaptchaService() { Request request = RequestCycle.get().getRequest(); HttpServletRequest httpRequest = ((WebRequest) request) .getHttpServletRequest(); String capText = captchaProducer.createText(); // store the text in the session httpRequest.getSession().setAttribute( Constants.KAPTCHA_SESSION_KEY, capText); // create the image with the text BufferedImage bi = captchaProducer.createImage(capText); return bi; } }); } }
4. CaptchaValidator
Créez un validateur personnalisé, nommé «CaptchaValidator», à utiliser pour valider l'entrée utilisateur et le comparer avec le code généré par Kaptcha.
Fichier: CaptchaValidator.java
package com.example.user; import javax.servlet.http.HttpServletRequest; import org.apache.wicket.Request; import org.apache.wicket.RequestCycle; import org.apache.wicket.protocol.http.WebRequest; import org.apache.wicket.validation.IValidatable; import org.apache.wicket.validation.validator.AbstractValidator; public class CaptchaValidator extends AbstractValidator{ private static final long serialVersionUID = 1L; private String INVALID_CODE = "captcha.invalid"; public void onValidate(IValidatable validatable) { String kaptchaReceived = (String) validatable.getValue(); Request request = RequestCycle.get().getRequest(); HttpServletRequest httpRequest = ((WebRequest) request) .getHttpServletRequest(); String kaptchaExpected = (String) httpRequest.getSession() .getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); if (kaptchaReceived == null || !kaptchaReceived.equalsIgnoreCase(kaptchaExpected)) { error(validatable); } } // validate on numm value as well @Override public boolean validateOnNullValue() { return true; } @Override protected String resourceKey() { return INVALID_CODE; } }
Fichier: package.properties
captcha.invalid = Incorrect answer, type words in image again!
5. Composants du guichet
Intégrez Kaptcha aux composants Wicket.
package com.example.user; import org.apache.wicket.PageParameters; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxFallbackLink; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.model.PropertyModel; public class KaptchaPage extends WebPage { private String captchaInput; public KaptchaPage(final PageParameters parameters) { final CaptchaImage captchaImage = new CaptchaImage("kaptchaImage"); captchaImage.setOutputMarkupId(true); TextFieldcaptchaTF = new TextField ("captcha", new PropertyModel (this, "captchaInput")); captchaTF.add(new CaptchaValidator()); Form> form = new Form ("form") { @Override protected void onSubmit() { info("Image words are correct!!!"); }; }; form.add(new AjaxFallbackLink("link") { @Override public void onClick(final AjaxRequestTarget target) { captchaImage.detach(); if (target != null) { target.addComponent(captchaImage); } else { // javascript is disable } } }.add(captchaImage)); form.add(captchaTF); add(form); add(new FeedbackPanel("feedback")); } }
NotecaptchaImage.detach();
permet de générer une nouvelle image captcha dynamiquement pendant que l'utilisateur clique sur l'image captcha.
Wicket + Kaptcha integration example
6. Demo
Démarrer et visiter -http://localhost:8080/WicketExamples/
Si l'importation est incorrecte:
Si l'entrée est correcte:
Téléchargez-le -Wicket-Kaptcha-Integration-Example.zip (10 Ko)