继上一篇文章jcaptcha验证码使用(一)
使用Spring配置jcaptha验证码
创建一个JavaWeb工程,引入相关依赖jar包
在web.xml中配置Spring代码
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-jcaptcha.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
spring-jcaptcha.xml
<?xml version="1.0" encoding="UTF-8"?> <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.2.xsd"> <!-- 构建生成图片服务 --> <bean id="imageCaptchaService" class="com.octo.captcha.service.multitype.GenericManageableCaptchaService"> <constructor-arg index="0" ref="imageEngine" /> <constructor-arg index="1" value="180" /> <constructor-arg index="2" value="200000" /> <constructor-arg index="3" value="75000" /> </bean> <!-- 构建生成图片引擎,可以传入多个ImageCaptchaFactory工厂 --> <bean id="imageEngine" class="com.octo.captcha.engine.GenericCaptchaEngine"> <constructor-arg index="0"> <list> <ref bean="imageCaptchaFactory" /> </list> </constructor-arg> </bean> <!-- 构件图片工厂 ,图片工厂包括FishEyeFactory和GimpyFactory 它们都继承自ImageCaptchaFactory抽象类 --> <bean id="imageCaptchaFactory" class="com.octo.captcha.image.gimpy.GimpyFactory"> <constructor-arg> <ref bean="wordgen" /> </constructor-arg> <constructor-arg> <ref bean="wordtoimage" /> </constructor-arg> </bean> <!-- 构件验证码上的文本生成类 --> <bean id="wordgen" class="com.octo.captcha.component.word.wordgenerator.ComposeDictionaryWordGenerator"> <constructor-arg index="0" ref="filedict" /> </bean> <!-- 构件文件字典类,读取文件字典 。该文件字典包含在jcaptcha-1.0-all.jar 包的toddlist.properties 文件 --> <bean id="filedict" class="com.octo.captcha.component.word.FileDictionary"> <constructor-arg index="0" value="toddlist" /> </bean> <!-- 构件一个从文本到图片的生成类 --> <bean id="wordtoimage" class="com.octo.captcha.component.image.wordtoimage.ComposedWordToImage"> <constructor-arg index="0"> <ref bean="fontGenRandom" /> </constructor-arg> <constructor-arg index="1"> <ref bean="backGenUni" /> </constructor-arg> <constructor-arg index="2"> <ref bean="simpleColoredPaster" /> </constructor-arg> </bean> <!-- 构件一个生成随机字体的类 。第一个参数是最小字体大小,第二个参数是最大字体大小,第三个参数是随机的字体列表 这里定义了5种类型的字体 --> <bean id="fontGenRandom" class="com.octo.captcha.component.image.fontgenerator.RandomFontGenerator"> <constructor-arg index="0"> <value>20</value> </constructor-arg> <constructor-arg index="1"> <value>25</value> </constructor-arg> <constructor-arg index="2"> <list> <bean class="java.awt.Font"> <constructor-arg index="0" value="Arial" /> <constructor-arg index="1" value="0" /> <constructor-arg index="2" value="10" /> </bean> <bean class="java.awt.Font"> <constructor-arg index="0" value="Tahoma" /> <constructor-arg index="1" value="1" /> <constructor-arg index="2" value="10" /> </bean> <bean class="java.awt.Font"> <constructor-arg index="0" value="Verdana" /> <constructor-arg index="1" value="0" /> <constructor-arg index="2" value="10" /> </bean> <bean class="java.awt.Font"> <constructor-arg index="0" value="Comic sans MS" /> <constructor-arg index="1" value="0" /> <constructor-arg index="2" value="10" /> </bean> <bean class="java.awt.Font"> <constructor-arg index="0" value="Lucida console" /> <constructor-arg index="1" value="0" /> <constructor-arg index="2" value="10" /> </bean> </list> </constructor-arg> </bean> <!-- 构件一个背景大小生成类 ,第一个参数是背景宽度,第二个参数是背景高度 --> <bean id="backGenUni" class="com.octo.captcha.component.image.backgroundgenerator.UniColorBackgroundGenerator"> <constructor-arg index="0"> <value>85</value> </constructor-arg> <constructor-arg index="1"> <value>40</value> </constructor-arg> </bean> <!-- 构件一个随机文本个数和颜色,第一个参数是最少文本个数,第二个参数是最多文本个数 --> <bean id="simpleColoredPaster" class="com.octo.captcha.component.image.textpaster.RandomTextPaster"> <constructor-arg index="0" value="4" /> <constructor-arg index="1" value="5" /> <constructor-arg type="com.octo.captcha.component.image.color.ColorGenerator" index="2" ref="colorGenRandomDark" /> <constructor-arg index="3" value="true" /> </bean> <!-- 构件一个随机的颜色,参数分别代表RGBA通道的取值范围 --> <bean id="colorGenRandomDark" class="com.octo.captcha.component.image.color.RandomRangeColorGenerator"> <constructor-arg index="0"> <list> <value>0</value> <value>255</value> </list> </constructor-arg> <constructor-arg index="1"> <list> <value>0</value> <value>185</value> </list> </constructor-arg> <constructor-arg index="2"> <list> <value>0</value> <value>200</value> </list> </constructor-arg> <constructor-arg index="3"> <list> <value>255</value> <value>255</value> </list> </constructor-arg> </bean> </beans>
创建一个生成验证码的Servlet
package cn.servlet; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.octo.captcha.service.CaptchaServiceException; import com.octo.captcha.service.image.ImageCaptchaService; public class JcaptchaServlet extends HttpServlet { private static final long serialVersionUID = -8021621053846019170L; public static final String CAPTCHA_IMAGE_FORMAT = "jpeg"; private ImageCaptchaService captchaService; @Override public void init() throws ServletException { WebApplicationContext appCtx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); captchaService = (ImageCaptchaService) BeanFactoryUtils.beanOfTypeIncludingAncestors(appCtx, ImageCaptchaService.class); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { byte[] captchaChallengeAsJpeg = null; ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream(); try { String captchaId = request.getSession().getId(); BufferedImage challenge = captchaService.getImageChallengeForID( captchaId, request.getLocale()); ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, jpegOutputStream); } catch (IllegalArgumentException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } catch (CaptchaServiceException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } captchaChallengeAsJpeg = jpegOutputStream.toByteArray(); // flush it in the response response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/" + CAPTCHA_IMAGE_FORMAT); ServletOutputStream responseOutputStream = response.getOutputStream(); responseOutputStream.write(captchaChallengeAsJpeg); responseOutputStream.flush(); responseOutputStream.close(); } }
在web.xml中注册这Servlet
<servlet> <servlet-name>springCaptcha</servlet-name> <servlet-class>cn.servlet.JcaptchaServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>springCaptcha</servlet-name> <url-pattern>/scgvc</url-pattern> </servlet-mapping>
创建html页面,引入jquery.js文件
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <script type="text/javascript" src="statics/js/jquery-1.8.3.min.js"></script> <script type="text/javascript"> //验证码刷新功能 function refreshCaptcha() { //Math.floor();向下取整 //jQuery效果,fadeIn() 方法使用淡入效果来显示被选元素,假如该元素是隐藏的。 $('#vcode').hide().attr( 'src', 'scgvc?'+ Math.floor(Math.random() * 100)).fadeIn(); } </script> <body> <form action="valiServlet" method="post"> <input type="text" name="customgvc"> <img onclick="refreshCaptcha()" id="vcode" title="点击更换" alt="验证图片" style="vertical-align: middle;" src="scgvc" height="30" width="80"> <input type="submit" value="提交"> </form> </body> </html>
编写一个验证Servlet并在web.xml中注册。(success.html和fail.html就不创建了)
package cn.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.octo.captcha.service.image.ImageCaptchaService; public class ValidateServlet extends HttpServlet { private static final long serialVersionUID = -7173743572400866269L; private ImageCaptchaService captchaService; @Override public void init() throws ServletException { WebApplicationContext appCtx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); captchaService = (ImageCaptchaService) BeanFactoryUtils.beanOfTypeIncludingAncestors(appCtx, ImageCaptchaService.class); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String captchaId = req.getSession().getId(); String validateCode = req.getParameter("customgvc"); Boolean validateResult = captchaService.validateResponseForID(captchaId, validateCode); if(validateResult) resp.sendRedirect("success.html"); else resp.sendRedirect("fail.html"); } }
<servlet> <servlet-name>validatServlet</servlet-name> <servlet-class>cn.servlet.ValidateServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>validatServlet</servlet-name> <url-pattern>/valiServlet</url-pattern> </servlet-mapping>