首先,文章是參考刺蝟的溫馴的。很是感謝提供這麼使用式例。javascript
maven形式,其餘方式自行下載html
<dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
這裏注意一下,不是springMvc的配置文件中java
<!-- kaptcha 驗證碼 --> <bean 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.border.color">105,179,90</prop> <prop key="kaptcha.textproducer.font.color">red</prop> <prop key="kaptcha.image.width">150</prop> <prop key="kaptcha.textproducer.font.size">55</prop> <prop key="kaptcha.image.height">55</prop> <prop key="kaptcha.session.key">kaptchaCode</prop> <prop key="kaptcha.textproducer.char.length">4</prop> <prop key="kaptcha.textproducer.font.names">宋體,楷體,微軟雅黑</prop> </props> </constructor-arg> </bean> </property> </bean>
import java.awt.image.BufferedImage; import javax.annotation.Resource; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.google.code.kaptcha.Constants; import com.google.code.kaptcha.Producer; @Controller public class KaptchaCon { @Resource Producer producer; @RequestMapping("login/img") public void handleRequest(HttpSession session, HttpServletResponse response) throws Exception { response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Pragma", "no-cache"); response.setContentType("image/jpeg"); String capText = producer.createText(); // store the text in the session session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText); // create the image with the text BufferedImage bi = producer.createImage(capText); ServletOutputStream out = response.getOutputStream(); // write the data out ImageIO.write(bi, "jpg", out); try { out.flush(); } finally { out.close(); } } }
<img src="${request.contextPath}/login/img" width="100%" height="100%" id="kaptchaImage" />
$(function() { $('#kaptchaImage').click( function() { $(this).attr( 'src', '${request.contextPath}/login/img?' + new Date().getTime()); }) });
關於配置問題,仍是繼續尋找資料看看吧!git