加入依赖
com.github.penggle
kaptcha
2.3.2
在 spring-mvc.xml 中加入
yes
105,179,90
blue
125
45
45
code
4
宋体,楷体,微软雅黑
属性具体配置:http://www.jianshu.com/p/e6c71bc37759
文本实现类:kaptcha.textproducer.impl
值为:com.google.code.kaptcha.text.impl.DefaultTextCreator
验证码值配置:kaptcha.textproducer.char.string
值:abcde2345678gfynmnpwx(随意你自己写)
验证码的长度:kaptcha.textproducer.char.length
值:
字体:kaptcha.textproducer.font.names
值:Arial,Courier
字体颜色:kaptcha.textproducer.font.color
值: r,g,b 或者 white,black,blue
文字间隔:kaptcha.textproducer.char.space
值:
干扰实现类:kaptcha.noise.impl
值:com.google.code.kaptcha.impl.DefaultNoise/NoNoise
干扰颜色:kaptcha.noise.color
值: r,g,b 或者 white,black,blue
图片样式:kaptcha.obscurificator.imp
l 值:
水纹com.google.code.kaptcha.impl.WaterRipple
;
鱼眼com.google.code.kaptcha.impl.FishEyeGimpy
;
阴影com.google.code.kaptcha.impl.ShadowGimpy
背景实现类:kaptcha.background.imp
l 值:com.google.code.kaptcha.impl.DefaultBackground
背景渐变色开始:kaptcha.background.clear.from
值:r,g,b 或者 white,black,blue
背景渐变色结束:kaptcha.background.clear.to
值:r,g,b 或者 white,black,blue
文字渲染器:kaptcha.word.impl
值:com.google.code.kaptcha.text.impl.DefaultWordRenderer
session中存放验证码的key键:kaptcha.session.key
值:KAPTCHA_SESSION_KEY
Contro;;er 中实现
/**
* 验证码生成
* @param request
* @param response
* @return
* @throws IOException
*/
@RequestMapping(value="/captcha-image")
public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println(request);
System.out.println(response);
// 从 session 获取验证码的 code 值
HttpSession session = request.getSession();
System.out.println(session);
String code = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
System.out.println(code);
// 设置清除浏览器的缓存
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/png");
// 设置 session
String capText = captchaProducer.createText();
System.out.println("设置session:" + capText);
session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
// 输出验证码
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(bi, "png", out);
out.flush();
out.close();
return null;
}
/**
* 验证码校验
* @param request
* @param response
* @param code_j
* @return
* @throws Exception
*/
@RequestMapping("/codeCheck")
public String codeCheck(HttpServletRequest request, HttpServletResponse response,
@RequestParam("code")String code_j) throws Exception {
HttpSession session = request.getSession();
String code = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
JSONObject json = new JSONObject();
if (code_j.equals(code)) {
json.put("ok", true);
} else {
json.put("ok", false);
}
ResponseUtil.write(response, json);
return null;
}
JSP 页面
验证码:
![](${path }/test/captcha-image)
看不清?换一张