Kaptchaはシンプルで使いやすいJavaライブラリを使用して、キャプチャ画像の検証を行います。このチュートリアルでは、KaptchaをWicketフレームワークとSpring ** を使って統合する方法を紹介します。
使用されるライブラリ:
-
Kaptcha v2.3.2
-
ウィケットv1.4.17
-
改札 – v1.4.17
-
Spring v3.0.5.RELEASE
1. Kaptchaを入手する
このhttp://code.google.com/p/kaptcha/issues/detail?id=12[thread]によれば、所有者はMavenが気に入らないので、ライブラリをローカルのMavenリポジトリに手動でインストールする必要があります。
{空} 1。 Kaptchaライブラリをhttp://code.google.com/p/kaptcha/から入手してください。2. Mavenコマンドの下で手動でインストールしてください。
mvn install:install-file -Dfile=c:\kaptcha-2.3.2.jar -DgroupId=com.google.code
-DartifactId=kaptcha -Dversion=2.3.2 -Dpackaging=jar
{空} 3。その後、pom.xmlファイルにkaptchaを含めることができます。
File:pom.xml
<dependency>
<groupId>com.google.code</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
2. Springを介したDefaultKaptcha
-
captchaProducer
という名前の ”
DefaultKaptcha ** “用のSpring Beanを作成します。
File:applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
<property name="config">
<bean class="com.google.code.kaptcha.util.Config">
<constructor-arg type="java.util.Properties" value="null">
</constructor-arg>
</bean>
</property>
</bean>
</beans>
3. CaptchaImage
Wicketの
NonCachingImage`を拡張し、
DynamicImageResource`クラスを使ってCaptchaイメージを動的に生成するCaptchaImageクラスを作成します。
File:CaptchaImage.java
package com.mkyong.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
”
CaptchaValidator
“というカスタムバリデーターを作成し、ユーザーの入力を検証し、Kaptcha生成コードと比較します。
File:CaptchaValidator.java
package com.mkyong.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<String> {
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;
}
}
File:package.properties
captcha.invalid = Incorrect answer, type words in image again!
5. Wicketコンポーネント
KaptchaをWicketコンポーネントと統合する。
package com.mkyong.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);
TextField<String> captchaTF = new TextField<String>("captcha",
new PropertyModel<String>(this, "captchaInput"));
captchaTF.add(new CaptchaValidator());
Form<?> form = new Form<Void>("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"));
}
}
-
注意** `captchaImage.detach();`はユーザーがcaptchaイメージをクリックしている間に新しいcaptchaイメージを動的に生成できるようにします。
<html>
<head>
<style>
.feedbackPanelINFO {
color: green;
}
.feedbackPanelERROR {
color: red;
}
</style>
</head>
<body>
<h1>Wicket + Kaptcha integration example</h1>
<div wicket:id="feedback"></div>
<form wicket:id="form">
<a wicket:id="link" title="Refresh image words">
<img wicket:id="kaptchaImage"/></a>
<br>
<label>Type the image words :</label>
<input type="text"wicket:id="captcha">
<input type="submit" value="Submit"/>
</form>
</body>
</html>
6.デモ
imputが正しくない場合:
入力が正しい場合:
ダウンロードする – リンク://wp-content/uploads/2009/05/Wicket-Kaptcha-Integration-Example.zip[Wicket-Kaptcha-Integration-Example.zip](10 KB)
参考文献
-
リンク://wicket/wicket-spring-integration-example/[Wicket Spring
統合例]。 link://maven/how-to-include-library-man-in-maven-local-repository/[インクルード
ライブラリをローカルMavenリポジトリに追加]