captchaProducer驗證碼生成
阿新 • • 發佈:2018-12-11
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 jpeg response.setContentType("image/jpeg"); // create the text for the image String capText = captchaProducer.createText(); System.err.println(capText); // store the text in the session request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText); // 存放到快取伺服器上,並把key記錄到cookie //CodeUtils.creatCode(capText, response, request); // create the image with the text BufferedImage bi = captchaProducer.createImage(capText); ServletOutputStream out = response.getOutputStream(); // write the data out ImageIO.write(bi, "jpg", out); try { out.flush(); } finally { out.close(); } }
ps:但是本地測試正常(圖一),部署到正式伺服器上(圖二)
(圖1)
(圖二)
只想說是什麼鬼,後臺查詢是發現伺服器上沒有安裝配置的字型Arial,安裝後重啟tomcat即可