1.导入依赖
<dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
2.配置kaptchaConfig.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <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.textproducer.font.color">black</prop> <!--验证码图片的宽度--> <prop key="kaptcha.image.width">100</prop> <!--验证码图片的高度--> <prop key="kaptcha.image.height">40</prop> <!--验证码字体的大小--> <prop key="kaptcha.textproducer.font.size">27</prop> <!--验证码保存在session的key--> <prop key="kaptcha.session.key">code</prop> <!--验证码输出的字符长度--> <prop key="kaptcha.textproducer.char.length">4</prop> <!--验证码的字体设置--> <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop> <!--验证码的取值范围--> <prop key="kaptcha.textproducer.char.string">0123456789</prop> <!--图片的样式--> <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.WaterRipple</prop> <!--干扰颜色,合法值: r,g,b 或者 white,black,blue.--> <!-- <prop key="kaptcha.noise.color">white</prop>--> <!--干扰实现类--> <prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.DefaultNoise</prop> <!--背景颜色渐变,开始颜色--> <prop key="kaptcha.background.clear.from">185,56,213</prop> <!--背景颜色渐变,结束颜色--> <prop key="kaptcha.background.clear.to">white</prop> <!--文字间隔--> <prop key="kaptcha.textproducer.char.space">3</prop> </props> </constructor-arg> </bean> </property> </bean> </beans>
3.启动类上添加注解
@ImportResource(locations={"classpath:kaptchaConfig.xml"})
4.配置一个获取验证码的Controller KaptchaController
package com.dyf.controller; import com.google.code.kaptcha.Producer; import org.springframework.beans.factory.annotation.Autowired; 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 org.springframework.web.servlet.ModelAndView; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.IOException; @Controller public class KaptchaController { @Autowired private Producer captchaProducer; //获取验证码 @RequestMapping(value = "verification", method = RequestMethod.GET) public ModelAndView verification(HttpServletRequest request, HttpServletResponse response) throws IOException { 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 jpeg response.setContentType("image/jpeg"); // create the text for the image String capText = captchaProducer.createText(); // store the text in the session request.getSession().setAttribute("code", capText); // create the image with the text BufferedImage bi = captchaProducer.createImage(capText); ServletOutputStream out = response.getOutputStream(); // write the data out ImageIO.write(bi, "jpg", out); try { out.flush(); } finally { out.close(); } return null; } //验证码验证 @RequestMapping("/checkCode") @ResponseBody public boolean imgvrifyControllerDefaultKaptcha(HttpServletRequest httpServletRequest) { String captchaId = (String) httpServletRequest.getSession().getAttribute("vrifyCode"); String parameter = httpServletRequest.getParameter("code"); if (!captchaId.equals(parameter)) { return false; } else { return true; } } }
5.jsp页面引入验证码
<img src="${pageContext.request.contextPath}/verification" style="cursor: pointer;" title="看不清?换一张" id="verification" style="cursor:pointer"><input type="text" class="form-control" id="code" name="code" required placeholder="请输入验证码">
6.添加个验证码刷新script在jsp中
<script> $(function () { // 刷新验证码 $("#verification").bind("click", function () { $(this).hide().attr('src', '${pageContext.request.contextPath}/verification?random=' + Math.random()).fadeIn(); }); }); </script>
7.验证码配合用户名密码登录验证的controller
@RequestMapping("/login") public String login(HttpServletRequest request, String name, String password, String code) { User user = userService.login(name, password); System.out.println(code); String captchaId = (String) request.getSession().getAttribute("code"); if (!captchaId.equals(code)) { System.out.println("error----------------"); } else { System.out.println("Right++++++++++++++++"); } String s = JSON.toJSONString(user); logger.info(s); System.out.println(user); return "ok"; }
注意 验证码在session中的名字是code