SpringMvc使用GoogleKaptcha生成验证码

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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>
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", 1, fontSize) -->
<prop key="s">宋体,楷体,微软雅⿊</prop>
</props>
</constructor-arg>
</bean>
</property>
</bean>
3、Controller的两个⽅法
package g.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" "/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
kaptcha.border.color 边框颜⾊默认为Color.BLACK
kaptcha.border.thickness 边框粗细度默认为1
kaptcha.producer.impl 验证码⽣成器默认为DefaultKaptcha
kaptcha.textproducer.impl 验证码⽂本⽣成器默认为DefaultTextCreator
kaptcha.textproducer.char.string 验证码⽂本字符内容范围默认为abcde2345678gfynmnpwx
kaptcha.textproducer.char.length 验证码⽂本字符长度默认为5
s 验证码⽂本字体样式默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize) kaptcha.textproducer.font.size 验证码⽂本字符⼤⼩默认为40
kaptcha.textproducer.font.color 验证码⽂本字符颜⾊默认为Color.BLACK
kaptcha.textproducer.char.space 验证码⽂本字符间距默认为2
kaptcha.noise.impl 验证码噪点⽣成对象默认为DefaultNoise
kaptcha.noise.color 验证码噪点颜⾊默认为Color.BLACK
kaptcha.obscurificator.impl 验证码样式引擎默认为WaterRipple
kaptcha.word.impl 验证码⽂本字符渲染默认为DefaultWordRenderer
kaptcha.background.impl 验证码背景⽣成器默认为DefaultBackground
kaptcha.background.clear.from 验证码背景颜⾊渐进默认为Color.LIGHT_GRAY
kaptcha.background.clear.to 验证码背景颜⾊渐进默认为Color.WHITE
kaptcha.image.width 验证码图⽚宽度默认为200
kaptcha.image.height 验证码图⽚⾼度默认为50
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

相关文档
最新文档