jcaptcha 验证码自定义扩展应用

本文章摘编、转载需要注明来源 http://write.blog.csdn.net/postedit/8575471


对于验证码的各个插件大家都应该熟悉不少了,但是我比较喜欢用jcaptcha这个插件,下面我演示自己的扩展使用


我使用的是DefaultManageableImageCaptchaService实现类根据源码的实现类改编过来的,至于其他的实现类有兴趣的可以自己去看下文档


然后就开始写我们的扩展类ImageCaptchaEngineExtend,该类要继承ListImageCaptchaEngine

/**
 * 自定义验证码内容样式
 * 
 * @author shadow
 * @email 124010356@qq.com
 */

public class ImageCaptchaEngineExtend extends ListImageCaptchaEngine {
           
         protected void buildInitialFactories() {

		// build filters
		WaterFilter water = new WaterFilter();

		water.setAmplitude(3d);
		water.setAntialias(true);
		water.setPhase(20d);
		water.setWavelength(70d);

		ImageDeformation backDef = new ImageDeformationByFilters(
				new ImageFilter[] {});
		ImageDeformation textDef = new ImageDeformationByFilters(
				new ImageFilter[] {});
		ImageDeformation postDef = new ImageDeformationByFilters(
				new ImageFilter[] { water });

		// word generator
		WordGenerator dictionnaryWords = new RandomWordGenerator(
				"abcdefhjkmnprstuvwxyz23456789");
		// wordtoimage components
		RandomRangeColorGenerator colors = new RandomRangeColorGenerator(
				new int[] { 0, 150 }, new int[] { 0, 150 },
				new int[] { 0, 150 });

		// Arial,Tahoma,Verdana,Helvetica,宋体,黑体,幼圆
		Font[] fonts = new Font[] { new Font("Arial", 0, 15),
				new Font("Tahoma", 0, 15), new Font("Verdana", 0, 15),
				new Font("Helvetica", 0, 15), new Font("宋体", 0, 15),
				new Font("黑体", 0, 15), new Font("幼圆", 0, 15) };

		// 设置字符以及干扰线
		RandomRangeColorGenerator lineColors = new RandomRangeColorGenerator(
				new int[] { 150, 255 }, new int[] { 150, 255 }, new int[] {
						150, 255 });

		TextPaster randomPaster = new DecoratedRandomTextPaster(new Integer(4),
				new Integer(4), colors, true,
				new TextDecorator[] { new LineTextDecorator(new Integer(1),
						lineColors) });
		BackgroundGenerator back = new UniColorBackgroundGenerator(new Integer(
				140), new Integer(45), Color.white);

		FontGenerator shearedFont = new RandomFontGenerator(new Integer(30),
				new Integer(0), fonts);
		// word2image 1
		WordToImage word2image;
		word2image = new DeformedComposedWordToImage(shearedFont, back,
				randomPaster, backDef, textDef, postDef);

		this.addFactory(new GimpyFactory(dictionnaryWords, word2image));

	}
}

然后写个单例调用我们的实现类

/**
 * Jcaptcha单例模式
 * 
 * @author shadow
 * @email 124010356@qq.com
 * @create 2012.04.28
 */
public class CaptchaServiceSingleton {

	// 不允许构造实例
	private CaptchaServiceSingleton() {
	}

	private static ImageCaptchaService instance = null;

	/**
	 * SimpleListSoundCaptchaEngine //还可以用声音 SpellerSoundCaptchaEngine
	 * SpellerSoundCaptchaEngine DefaultGimpyEngineCaptcha
	 * BaffleListGimpyEngineCaptcha BasicListGimpyEngineCaptcha
	 * DeformedBaffleListGimpyEngineCaptcha DoubleRandomListGimpyEngineCaptcha
	 * SimpleListImageCaptchaEngineCaptcha SimpleFishEyeEngineCaptcha
	 */
	// 传入样式类
	static {
		instance = new DefaultManageableImageCaptchaService(
				new FastHashMapCaptchaStore(), new ImageCaptchaEngineExtend(),
				180, 100000, 75000);
	}

	public static ImageCaptchaService getInstance() {
		return instance;
	}

}


再来个servlet类

@SuppressWarnings("serial")
public class ImageCaptchaServlet extends HttpServlet {

	public void init(ServletConfig servletConfig) throws ServletException {
		super.init(servletConfig);
	}

	protected void doGet(HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse) throws ServletException,
			IOException {

		byte[] captchaChallengeAsJpeg = null;
		// the output stream to render the captcha image as jpeg into
		ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
		try {
			// get the session id that will identify the generated captcha.
			// the same id must be used to validate the response, the session id
			// is a good candidate!
			String captchaId = httpServletRequest.getSession().getId();
			// call the ImageCaptchaService getChallenge method
			BufferedImage challenge = CaptchaServiceSingleton.getInstance()
					.getImageChallengeForID(captchaId,
							httpServletRequest.getLocale());

			// a jpeg encoder
			JPEGImageEncoder jpegEncoder = JPEGCodec
					.createJPEGEncoder(jpegOutputStream);
			jpegEncoder.encode(challenge);
		} catch (IllegalArgumentException e) {
			httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		} catch (CaptchaServiceException e) {
			httpServletResponse
					.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			return;
		}

		captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

		// flush it in the response
		httpServletResponse.setHeader("Cache-Control", "no-store");
		httpServletResponse.setHeader("Pragma", "no-cache");
		httpServletResponse.setDateHeader("Expires", 0);
		httpServletResponse.setContentType("image/jpeg");
		ServletOutputStream responseOutputStream = httpServletResponse
				.getOutputStream();
		responseOutputStream.write(captchaChallengeAsJpeg);
		responseOutputStream.flush();
		responseOutputStream.close();
	}
}


接着我们来配置web.xml

<!-- jcaptcha filter -->
	<servlet>
		<servlet-name>jcaptcha</servlet-name>
		<servlet-class>
			com.shadow.extras.jcaptcha.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看效果图

jcaptcha 验证码自定义扩展应用

jcaptcha 验证码自定义扩展应用

上一篇:spring security3教程系列--如何踢出用户


下一篇:GO从入门到进阶教程系列 - 研发高性能ORM框架操作mysql篇