Springboot 生成验证码
技术:springboot+kaptcha+session
概述
场景介绍 验证码,用于web网站。用户点击验证码图片后,生成验证码。提交后,用户输入验证码和Session验证码,进行校验。
详细
一、目录结构
二、功能讲解
(1)验证码配置文件
打开KaptchaConfig.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | @Component public class KaptchaConfig { @Bean public 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" ); //文本集合,验证码值从此集合中获取 properties.setProperty( "kaptcha.textproducer.char.string" , "01234567890" ); //验证码长度 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; } } |
详细配置说明:https://blog.csdn.net/elephantboy/article/details/52795309
(2)生成验证码方法
打开CommonUtil.java,这是一个公共方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | public class CommonUtil { /** * 生成验证码图片 * @param request 设置session * @param response 转成图片 * @param captchaProducer 生成图片方法类 * @param validateSessionKey session名称 * @throws Exception */ public static void validateCode(HttpServletRequest request, HttpServletResponse response, DefaultKaptcha captchaProducer, String validateSessionKey) 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 jpeg response.setContentType( "image/jpeg" ); // create the text for the image String capText = captchaProducer.createText(); // store the text in the session request.getSession().setAttribute(validateSessionKey, 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(); } } } |
(3)验证码控制类
打开MainController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | @Controller public class MainController { @Resource private DefaultKaptcha captchaProducer; @RequestMapping (value = { "/" }) public String index() { return "/index" ; } /** * 登录验证码SessionKey */ public static final String LOGIN_VALIDATE_CODE = "login_validate_code" ; /** * 登录验证码图片 */ @RequestMapping (value = { "/loginValidateCode" }) public void loginValidateCode(HttpServletRequest request, HttpServletResponse response) throws Exception{ CommonUtil.validateCode(request,response,captchaProducer,LOGIN_VALIDATE_CODE); } /** * 检查验证码是否正确 */ @RequestMapping ( "/checkLoginValidateCode" ) @ResponseBody public HashMap checkLoginValidateCode(HttpServletRequest request, @RequestParam ( "validateCode" )String validateCode) { String loginValidateCode = request.getSession().getAttribute(LOGIN_VALIDATE_CODE).toString(); HashMap<String,Object> map = new HashMap<String,Object>(); if (loginValidateCode == null ){ map.put( "status" , null ); //验证码过期 } else if (loginValidateCode.equals(validateCode)){ map.put( "status" , true ); //验证码正确 } else if (!loginValidateCode.equals(validateCode)){ map.put( "status" , false ); //验证码不正确 } map.put( "code" , 200 ); return map; } } |
(4)前端页面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | <! DOCTYPE html> < html lang="en"> < head > < meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> < title >SpringBoot 生成验证码</ title > < script type="text/javascript" src="/js/jquery/jquery-3.3.1.min.js"></ script > < script type='text/javascript'> $(function () { $("#validateCode").keyup(function(){ checkLoginValidateCode($(this).val()); }); }); function uploadLoginValidateCode() { $("#loginValidateCode").attr("src","/loginValidateCode?random="+new Date().getMilliseconds()); } function checkLoginValidateCode(validateCode) { var error = $("#validateCode").parent().next(); if(validateCode != null && validateCode != ""){ $.ajax({ type: "POST", async:false, url: "/checkLoginValidateCode?validateCode="+validateCode, success : function(json) { if(json != null && json.code == 200 && json.status != null) { if (json.status == true) { error.html("恭喜你验证码,正确!!!!!"); } else if(json.status == false){ error.html("验证码错误,请重新输入"); }else{ error.html("验证码过期,请重新输入"); uploadLoginValidateCode(); } } return false; }, error:function(XMLHttpRequest,textStatus,errorThrown){ alert("服务器错误!状态码:"+XMLHttpRequest.status); // 状态 console.log(XMLHttpRequest.readyState); // 错误信息 console.log(textStatus); return false; } }); }else{ error.html("请输入验证码!"); } } </ script > </ head > < body > 验证码: < img id="loginValidateCode" height="40" width="150" style="cursor: pointer;" src="/loginValidateCode" onclick="uploadLoginValidateCode();"> < p > 你输入的内容:< input type="text" id="validateCode" name="validateCode" /> </ p > < p style="color: red"></ p > </ body > </ html > |
三、运行
吐槽环节:百度的搜java 验证码,太坑爹了,各种各样复杂,非常不通用,还有一些不能运行的。忍不了忍不了,自己整合一个,最后找到google kaptcha 工具 vary good !!!
谢谢大家观看~
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架