使用谷歌的kaptcha进行验证码验证
我的实现思路
1. jsp页面发出请求到Controller
1. Controller层接收请求去寻找对应的验证码视图
1. 验证码视图层生成验证码
1. 返会给jsp页面进行验证码显示
具体实现
引入jar包
<!--谷歌验证码生成 jar--><dependency><groupId>com.google.code</groupId><artifactId>kaptcha</artifactId><version>${kaptcha.version}</version></dependency><!--/谷歌验证码生成 jar-->
jsp页面
<input type="text" placeholder="请输入验证码" value="" id="inputCode" /><img src="${pageurl }/identify/getImageCode" id="reflush"onclick="$('#reflush').attr('src','/identify/getImageCode');" />
验证码刷新js
$(function(){//验证码的验证$("#inputCode").blur(function(){var $value=$(this).val();if ($value=="") {alert("验证码不能为空");}else{$.post("/identify/codeIsTrue",{"inputCode":$value},function(data){alert(data.result);},"json");}$('#reflush').attr('src','/identify/getImageCode');});
});
Controller层
package com.education.project.web.controller;import java.util.HashMap;
import java.util.Map;import javax.servlet.http.HttpSession;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;import com.google.code.kaptcha.Constants;
@Controller
@RequestMapping("/identify")
public class IdentityCodeController {@RequestMapping("/code")public String code(){return "/code/index";}@RequestMapping("/getImageCode")public String createCode(){return "kaptchaImageCodeView";}@RequestMapping(value="/codeIsTrue", method=RequestMethod.POST)public @ResponseBody Map<String, Object> codeIsTrue(String inputCode,HttpSession session){Map<String, Object> map=new HashMap<>();if (inputCode.equals(session.getAttribute(Constants.KAPTCHA_SESSION_KEY))) {map.put("result", "验证成功");}else{map.put("result", "验证失败,你输入的验证码为:"+inputCode+",正确的验证码为:"+session.getAttribute(Constants.KAPTCHA_SESSION_KEY));}return map;}
}
验证码的视图层(自定义视图解析器)view.xml
<bean id="kaptchaImageCodeView" class="com.education.project.web.view.KaptchaImageCodeView"p:captchaProducer-ref="captchaProducer"/>
验证码的实现类(继承springmvc的AbstractView)
package com.education.project.web.view;import java.awt.image.BufferedImage;
import java.util.Map;import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.view.AbstractView;import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;public class KaptchaImageCodeView extends AbstractView {private Producer captchaProducer = null;public void setCaptchaProducer(Producer captchaProducer) {this.captchaProducer = captchaProducer;}@Overrideprotected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,HttpServletResponse response) throws Exception {// Set to expire far in the past.response.setDateHeader("Expires", 0);// Set standard HTTP/1.1 no-cache headers.response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");// Set IE extended HTTP/1.1 no-cache headers (use addHeader).response.addHeader("Cache-Control", "post-check=0, pre-check=0");// Set standard HTTP/1.0 no-cache header.response.setHeader("Pragma", "no-cache");// return a jpegresponse.setContentType("image/jpeg");// create the text for the imageString capText = captchaProducer.createText();// store the text in the sessionrequest.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);// create the image with the textBufferedImage bi = captchaProducer.createImage(capText);ServletOutputStream out = response.getOutputStream();// write the data outImageIO.write(bi, "jpg", out);out.flush();out.close();}}
在springmvc的配置文件中集成自定义视图
<bean class="org.springframework.web.servlet.view.XmlViewResolver"p:order="10"p:location="classpath:views.xml"/>
验证码样式配置(具体配置参照以下文档)
<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha"><property name="config"><bean class="com.google.code.kaptcha.util.Config"><constructor-arg type="java.util.Properties"><props><prop key="kaptcha.border">no</prop><prop key="kaptcha.border.color">105,179,90</prop><prop key="kaptcha.image.width">160</prop><prop key="kaptcha.image.height">50</prop><prop key="kaptcha.session.key">code</prop><prop key="kaptcha.textproducer.font.color">red</prop><prop key="kaptcha.textproducer.font.size">35</prop><prop key="kaptcha.textproducer.char.space">3</prop><prop key="kaptcha.textproducer.char.length">5</prop><!-- 配置中文 <prop key="kaptcha.textproducer.impl">com.google.code.kaptcha.text.impl.ChineseTextProducer</prop>--> <prop key="kaptcha.textproducer.font.names">彩云,宋体,楷体,微软雅黑</prop><prop key="kaptcha.background.clear.from">white</prop><prop key="kaptcha.background.clear.to">black</prop></props></constructor-arg></bean></property>