第一步导包
<!-- 验证码--> <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
第二步在spring配置相关参数
<!--验证码配置--> <bean id="kaptchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha"> <property name="config"> <bean class="com.google.code.kaptcha.util.Config"> <constructor-arg> <props> <!-- 验证码宽度 --> <prop key="kaptcha.image.width">130</prop> <!-- 验证码高度 --> <prop key="kaptcha.image.height">35</prop> <!-- 生成验证码内容范围 --> <prop key="kaptcha.textproducer.char.string">0123456789AKWUEHPMRX</prop> <!-- 验证码个数 --> <prop key="kaptcha.textproducer.char.length">4</prop> <!-- 是否有边框 --> <prop key="kaptcha.border">no</prop> <!-- 边框颜色 --> <prop key="kaptcha.border.color">105,179,90</prop> <!-- 边框厚度 --> <prop key="kaptcha.border.thickness">1</prop> <!-- 验证码字体颜色 --> <prop key="kaptcha.textproducer.font.color">black</prop> <!-- 验证码字体大小 --> <prop key="kaptcha.textproducer.font.size">30</prop> <!-- 验证码所属字体样式 --> <prop key="kaptcha.textproducer.font.names">微软雅黑</prop> <!-- 干扰线颜色 --> <prop key="kaptcha.noise.color">yellow</prop> <!-- 验证码文本字符间距 --> <prop key="kaptcha.textproducer.char.space">8</prop> <!-- 图片样式 :阴影--> <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.ShadowGimpy</prop> </props> </constructor-arg> </bean> </property> </bean>
第三步用form表单提交数据,下面是验证码的前端代码
<div class="form-group"> <label for="password" class="col-sm-3 control-label">验证码:</label> <div class="col-sm-4"> <input type="text" class="form-control" placeholder="验证码" name="captchacode"> </div> <div class="col-sm-2"> <img id="kaptchaImage" src="${pageContext.request.contextPath}/user/getVerifyCode" οnclick="change();"> </div> </div>
对应的change()函数,点击图片就刷新验证码
<script> function change() { $('#kaptchaImage').click(function () { $(this).attr('src', '${pageContext.request.contextPath}/user/getVerifyCode?' + Math.floor(Math.random() * 100)); }) } </script>
第四步:下面是controller层生产验证码的代码
@Autowired private Producer kaptchaProducer; //生成验证码 @RequestMapping("/getVerifyCode") public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response){ 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 = kaptchaProducer.createText();//生产验证码 request.getSession().setAttribute("verifyCode", capText); BufferedImage bi = kaptchaProducer.createImage(capText);//把验证码渲染到图片 ServletOutputStream out = null; try { out = response.getOutputStream();//得到输出流 ImageIO.write(bi, "jpg", out);//把图片以输出流的方式输出 } catch (IOException e) { e.printStackTrace(); } try { out.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }
验证验证码的代码就是把 request.getSession().setAttribute("verifyCode", capText);里面的内容和form表单里面的文本进行比较就好