原文参考 这里
安装
Add jcaptcha-all.jar (provided in bin-distribution ) and ehcache.jar (not provided see ehcache site ) to your application class path, ie in you WEB-INF/lib folder.
实例一个jcaptcha服务,注意,必须是单例模式的
import
com.octo.captcha.service.image.ImageCaptchaService;
import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;
public class CaptchaServiceSingleton{
private static ImageCaptchaServiceinstance = new DefaultManageableImageCaptchaService();
public static ImageCaptchaServicegetInstance(){
return instance;
}
}
import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;
public class CaptchaServiceSingleton{
private static ImageCaptchaServiceinstance = new DefaultManageableImageCaptchaService();
public static ImageCaptchaServicegetInstance(){
return instance;
}
}
注:以上是默认的一个实现,下面是其他更多的实现
- SimpleListSoundCaptchaEngine //还可以用声音,真爽哦
- SpellerSoundCaptchaEngine
- SpellerSoundCaptchaEngine
- DefaultGimpyEngineCaptcha
- BaffleListGimpyEngineCaptcha
- BasicListGimpyEngineCaptcha
- DeformedBaffleListGimpyEngineCaptcha
- DoubleRandomListGimpyEngineCaptcha
- SimpleListImageCaptchaEngineCaptcha
- SimpleFishEyeEngineCaptcha
编写一个产生图片的servlet
import
com.octo.captcha.service.CaptchaServiceException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ImageCaptchaServlet extends HttpServlet{
public void init(ServletConfigservletConfig) throws ServletException{
super .init(servletConfig);
}
protected void doGet(HttpServletRequesthttpServletRequest,HttpServletResponsehttpServletResponse) throws ServletException,IOException{
byte []captchaChallengeAsJpeg = null ;
// theoutputstreamtorenderthecaptchaimageasjpeginto
ByteArrayOutputStreamjpegOutputStream = new ByteArrayOutputStream();
try {
// getthesessionidthatwillidentifythegeneratedcaptcha.
// thesameidmustbeusedtovalidatetheresponse,thesessionidisagoodcandidate!
StringcaptchaId = httpServletRequest.getSession().getId();
// calltheImageCaptchaServicegetChallengemethod
BufferedImagechallenge =
CaptchaServiceSingleton.getInstance().getImageChallengeForID(captchaId,
httpServletRequest.getLocale());
// ajpegencoder
JPEGImageEncoderjpegEncoder =
JPEGCodec.createJPEGEncoder(jpegOutputStream);
jpegEncoder.encode(challenge);
} catch (IllegalArgumentExceptione){
httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
return ;
} catch (CaptchaServiceExceptione){
httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return ;
}
captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
// flushitintheresponse
httpServletResponse.setHeader( " Cache-Control " , " no-store " );
httpServletResponse.setHeader( " Pragma " , " no-cache " );
httpServletResponse.setDateHeader( " Expires " , 0 );
httpServletResponse.setContentType( " image/jpeg " );
ServletOutputStreamresponseOutputStream =
httpServletResponse.getOutputStream();
responseOutputStream.write(captchaChallengeAsJpeg);
responseOutputStream.flush();
responseOutputStream.close();
}
}
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ImageCaptchaServlet extends HttpServlet{
public void init(ServletConfigservletConfig) throws ServletException{
super .init(servletConfig);
}
protected void doGet(HttpServletRequesthttpServletRequest,HttpServletResponsehttpServletResponse) throws ServletException,IOException{
byte []captchaChallengeAsJpeg = null ;
// theoutputstreamtorenderthecaptchaimageasjpeginto
ByteArrayOutputStreamjpegOutputStream = new ByteArrayOutputStream();
try {
// getthesessionidthatwillidentifythegeneratedcaptcha.
// thesameidmustbeusedtovalidatetheresponse,thesessionidisagoodcandidate!
StringcaptchaId = httpServletRequest.getSession().getId();
// calltheImageCaptchaServicegetChallengemethod
BufferedImagechallenge =
CaptchaServiceSingleton.getInstance().getImageChallengeForID(captchaId,
httpServletRequest.getLocale());
// ajpegencoder
JPEGImageEncoderjpegEncoder =
JPEGCodec.createJPEGEncoder(jpegOutputStream);
jpegEncoder.encode(challenge);
} catch (IllegalArgumentExceptione){
httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
return ;
} catch (CaptchaServiceExceptione){
httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return ;
}
captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
// flushitintheresponse
httpServletResponse.setHeader( " Cache-Control " , " no-store " );
httpServletResponse.setHeader( " Pragma " , " no-cache " );
httpServletResponse.setDateHeader( " Expires " , 0 );
httpServletResponse.setContentType( " image/jpeg " );
ServletOutputStreamresponseOutputStream =
httpServletResponse.getOutputStream();
responseOutputStream.write(captchaChallengeAsJpeg);
responseOutputStream.flush();
responseOutputStream.close();
}
}
为servlet修改web.xml配置文件
<
servlet
>
< servlet-name > jcaptcha </ servlet-name >
< servlet-class > ImageCaptchaServlet </ servlet-class >
< load-on-startup > 0 </ load-on-startup >
</ servlet >
< servlet-mapping >
< servlet-name > jcaptcha </ servlet-name >
< url-pattern > /jcaptcha </ url-pattern >
</ servlet-mapping >
< servlet-name > jcaptcha </ servlet-name >
< servlet-class > ImageCaptchaServlet </ servlet-class >
< load-on-startup > 0 </ load-on-startup >
</ servlet >
< servlet-mapping >
< servlet-name > jcaptcha </ servlet-name >
< url-pattern > /jcaptcha </ url-pattern >
</ servlet-mapping >
编写你的客户端的展示
<
img
src
="jcaptcha"
>
< input type ='text' name ='j_captcha_response' value ='' >
< input type ='text' name ='j_captcha_response' value ='' >
上面的src="jcaptcha" 就是调用了上面的servlet,text里是用户填写的确认验证码
后台逻辑验证
BooleanisResponseCorrect
=
Boolean.FALSE;
// remenberthatweneedanidtovalidate!
StringcaptchaId = httpServletRequest.getSession().getId();
// retrievetheresponse
Stringresponse = httpServletRequest.getParameter( " j_captcha_response " );
// CalltheServicemethod
try {
isResponseCorrect = CaptchaServiceSingleton.getInstance().validateResponseForID(captchaId,
response);
} catch (CaptchaServiceExceptione){
// shouldnothappen,maybethrowniftheidisnotvalid
}
// remenberthatweneedanidtovalidate!
StringcaptchaId = httpServletRequest.getSession().getId();
// retrievetheresponse
Stringresponse = httpServletRequest.getParameter( " j_captcha_response " );
// CalltheServicemethod
try {
isResponseCorrect = CaptchaServiceSingleton.getInstance().validateResponseForID(captchaId,
response);
} catch (CaptchaServiceExceptione){
// shouldnothappen,maybethrowniftheidisnotvalid
}
OK,大功告成了.