1.pom.xml中导入架包
<dependency><groupId>com.google.code</groupId><artifactId>kaptcha</artifactId><version>2.3.2</version></dependency>
2.web-mvc.xml添加验证码的主要配置,如颜色等
<!-- 验证码 --><bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha"><property name="config"><bean class="com.google.code.kaptcha.util.Config"><constructor-arg><props><prop key="kaptcha.border">no</prop><prop key="kaptcha.textproducer.font.color">20,15,90</prop><prop key="kaptcha.textproducer.char.length">4</prop><prop key="kaptcha.image.width">124</prop><prop key="kaptcha.textproducer.char.space">1</prop><prop key="kaptcha.textproducer.font.size">30</prop><prop key="kaptcha.image.height">35</prop><prop key="kaptcha.textproducer.font.names">Arial</prop><prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.NoNoise</prop><prop key="kaptcha.background.clear.from">white</prop><prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.ShadowGimpy</prop></props></constructor-arg></bean></property></bean>
3.生成验证码图片
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {response.setDateHeader("Expires", 0);// Set standard HTTP/1.1 no-cache headers.response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");// Set IE extended HTTP/1.1 no-cache headers (use addHeader).response.addHeader("Cache-Control", "post-check=0, pre-check=0");// Set standard HTTP/1.0 no-cache header.response.setHeader("Pragma", "no-cache");// return a jpegresponse.setContentType("image/jpeg");// create the text for the imageString capText = captchaProducer.createText();System.err.println(capText);// store the text in the sessionrequest.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);// 存放到缓存服务器上,并把key记录到cookie//CodeUtils.creatCode(capText, response, request);// create the image with the textBufferedImage bi = captchaProducer.createImage(capText);ServletOutputStream out = response.getOutputStream();// write the data outImageIO.write(bi, "jpg", out);try {out.flush();} finally {out.close();}}
ps:但是本地测试正常(图一),部署到正式服务器上(图二)
(图1)
(图二)
只想说是什么鬼,后台查询是发现服务器上没有安装配置的字体Arial,安装后重启tomcat即可