SpringMvc使用GoogleKaptcha生成验证码
前言:google captcha 是google生成验证码的一个工具类,其原理是将随机生成字符串保存到session中,同时以图片的形式返回给页面,之后前台页面提交到后台进行对比。 1、jar包准备 官方提供的pom应该是 <dependency> <groupId>com.google.code.kaptcha</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency> 但是下载不下来,我在阿里的maven仓库找到的pom如下: <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency> 测试可以正常下载,这里推荐阿里的maven仓库,下载速度还行,挺稳定,附地址:http://maven.aliyun.com/nexus/#welcome 2、spring bean的配置 <!-- google kaptcha的相关配置--> <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha"> <property name="config"> <bean class="com.google.code.kaptcha.util.Config"> <constructor-arg> <props> <!-- 是否有边框 可选yes 或者 no --> <prop key="kaptcha.border">yes</prop> <!-- 边框颜色 --> <prop key="kaptcha.border.color">105,179,90</prop> <!-- 验证码文本字符颜色 --> <prop key="kaptcha.textproducer.font.color">blue</prop> <!-- 验证码文本字符大小 --> <prop key="kaptcha.textproducer.font.size">45</prop> <!-- 验证码图片的宽度 默认200 --> <prop key="kaptcha.image.width">125</prop> <!-- 验证码图片的高度 默认50 --> <prop key="kaptcha.image.height">45</prop> <!-- 验证码文本字符长度 默认为5 --> <prop key="kaptcha.textproducer.char.length">4</prop> <!-- 验证码文本字体样式 默认为new Font("Arial",1,fontSize),new Font("Courier",fontSize) --> <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop> </props> </constructor-arg> </bean> </property> </bean> 3、Controller的两个方法 package com.ccg.controller; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.PrintWriter; import javax.annotation.Resource; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.google.code.kaptcha.Constants; import com.google.code.kaptcha.Producer; @Controller @RequestMapping("captcha") public class CaptchaController { @Resource private Producer captchaProducer; /** * * 获取验证码图片 * @author ccg * @param request * @param response * @return * @throws IOException * Created 2017年1月17日 下午5:07:28 */ @RequestMapping("getCaptchaCode") public ModelAndView getCaptchaCode(HttpServletRequest request,HttpServletResponse response) throws IOException{ HttpSession session = request.getSession(); 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 = captchaProducer.createText(); session.setAttribute(Constants.KAPTCHA_SESSION_KEY,capText); System.out.println("生成验证码文本===="+capText); //利用生成的字符串构建图片 BufferedImage bi = captchaProducer.createImage(capText); ServletOutputStream out = response.getOutputStream(); ImageIO.write(bi,"jpg",out); try { out.flush(); } finally { out.close(); } return null; } /** * * 前端输入的验证码与生成的对比 * @author ccg * @param request * @param response * @param captchaCode * Created 2017年1月17日 下午5:34:23 */ @RequestMapping("checkCaptchaCode") public void checkCaptchaCode(HttpServletRequest request,HttpServletResponse response,@RequestParam("captchaCode") String captchaCode){ System.out.println("页面输入验证码===="+captchaCode); response.setCharacterEncoding("UTF-8"); response.setHeader("Pragma","No-cache"); response.setHeader("Cache-Control","no-cache"); response.setDateHeader("Expires",0); String generateCode =(String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY); String result = ""; if(generateCode.equals(captchaCode)){ result = "验证成功"; }else{ result = "输入错误"; } PrintWriter out = null; try { out = response.getWriter(); } catch (IOException e) { e.printStackTrace(); } out.print(result); out.flush(); } } 4、前台页面代码 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="${pageContext.request.contextPath}/js/jquery.min.js" type="text/javascript"></script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 生成的验证码:<img id="changeCaptcha" src="http://127.0.0.1/captcha/getCaptchaCode.htm"> <a href="javascript:changeCaptcha()" rel="external nofollow" >看不清,换一张</a> <br> <br> 请输入验证码:<input id="captchaCode" type="text"> <input type="button" value="提交验证" onclick="checkCaptcha()"> </body> <script type="text/javascript"> //获取验证码图片 function changeCaptcha(){ $("#changeCaptcha").attr("src","http://127.0.0.1/captcha/getCaptchaCode.htm"); } //验证输入的验证码 function checkCaptcha(){ var captchaCode = $("#captchaCode").val(); $.ajax({ type:'post',async : false,url:'http://127.0.0.1/captcha/checkCaptchaCode.htm',data:{"captchaCode" : captchaCode},success:function(res){ alert(res); } }); } </script> </html> 需要注意到引用了jquery.min.js 5、运行效果 附Google Captcha 可配置项 kaptcha.border 是否有边框 默认为true 我们可以自己设置yes,no 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |