使用kaptcha生产纯数字验证码录
- 1引入依赖
- 2编写容器配置类
- 3生产验证码工具类
- 4控制层逻辑
- 5登陆页面设置
- 6 访问你的登录接口测试
1引入依赖
<!-- 验证码 依赖--><dependency><groupId>com.github.axet</groupId><artifactId>kaptcha</artifactId><version>0.0.9</version></dependency>
2编写容器配置类
package com.hengquanrui.controller;import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
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 javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;@Controller
@RequestMapping("/kaptcha")
public class CaptchaController {@Autowiredprivate Producer captchaProducer;@CrossOrigin@RequestMapping("getKaptchaImage")public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {HttpSession session = request.getSession();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 sessionsession.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);// String code = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
// System.out.println("******************验证码是: " + code + "******************");// create the image with the textBufferedImage bi = captchaProducer.createImage(capText);ServletOutputStream out = response.getOutputStream();// write the data outImageIO.write(bi, "jpg", out);try {out.flush();} finally {out.close();}return null;}}
3生产验证码工具类
@Component
@CrossOrigin
public class KaptchaConfig {@Beanpublic DefaultKaptcha getDefaultKaptcha() {com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha();Properties properties = new Properties();// 图片边框properties.setProperty("kaptcha.border", "no");// 边框颜色properties.setProperty("kaptcha.border.color", "black");//边框厚度properties.setProperty("kaptcha.border.thickness", "1");// 图片宽properties.setProperty("kaptcha.image.width", "200");// 图片高properties.setProperty("kaptcha.image.height", "50");//图片实现类properties.setProperty("kaptcha.producer.impl", "com.google.code.kaptcha.impl.DefaultKaptcha");//文本实现类properties.setProperty("kaptcha.textproducer.impl", "com.google.code.kaptcha.text.impl.DefaultTextCreator");//文本集合,验证码值从此集合中获取 0qwertyuiopasdfghjklzxcvbnmproperties.setProperty("kaptcha.textproducer.char.string", "0123456789");//验证码长度properties.setProperty("kaptcha.textproducer.char.length", "4");//字体properties.setProperty("kaptcha.textproducer.font.names", "宋体");//字体颜色properties.setProperty("kaptcha.textproducer.font.color", "black");//文字间隔properties.setProperty("kaptcha.textproducer.char.space", "5");//干扰实现类properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.DefaultNoise");//干扰颜色properties.setProperty("kaptcha.noise.color", "blue");//干扰图片样式properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.WaterRipple");//背景实现类properties.setProperty("kaptcha.background.impl", "com.google.code.kaptcha.impl.DefaultBackground");//背景颜色渐变,结束颜色properties.setProperty("kaptcha.background.clear.to", "white");//文字渲染器properties.setProperty("kaptcha.word.impl", "com.google.code.kaptcha.text.impl.DefaultWordRenderer");Config config = new Config(properties);defaultKaptcha.setConfig(config);return defaultKaptcha;}}
4控制层逻辑
@RequestMapping(value = "/login", method = RequestMethod.POST)@ResponseBodypublic Map loginVerification(HttpServletRequest request, String username, String password, @RequestParam("code")String code){HashMap<String, Object> map = new HashMap<>();String sessionCode = (String)request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);System.out.println(" session中获取的验证码: " + sessionCode);if (!code.equalsIgnoreCase(sessionCode)){map.put("code",404);map.put("msg","验证码错误!");return map;}//1.获取SubjectSubject user = SecurityUtils.getSubject();//2.封装用户信息UsernamePasswordToken token = new UsernamePasswordToken(username, password);//3.执行登录方法try {user.login(token);map.put("code",200);map.put("msg","登陆成功!");return map;} catch (AuthenticationException e) {e.printStackTrace();}map.put("code",404);map.put("msg","登陆失败!");return map;}
5登陆页面设置
前端核心代码
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script><div class="form-group"><input type="text" class="form-control" name="code" placeholder="验证码" required=""><span class="p-new-code l-mar-r15"> <img src="http://127.0.0.1:8081/kaptcha/getImage" class="reloadImage" id="reloadImage"width="121" height="40"/> </span><a href="javaScript:;" class="l-color9 reloadImage">看不清楚,换一张</a></div><script>$(".reloadImage").click(function () {//获取当前的时间作为参数,无具体意义var timenow = new Date().getTime();$('#reloadImage').attr("src", "http://127.0.0.1:8080/kaptcha/getImage?date=" + timenow);});</script>
6 访问你的登录接口测试
注意问题:1,以上如出现图片加载不出来,可以尝试把生成图片接口访问权限放开。
2,如果涉及到跨域问题,可以把127.0.0.1改成localhost。
3,可以在properties.setProperty(…),设置纯数字验证码,或者文字验证码。