kaptcha生成验证码
kaptcha配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | @Configuration public class KaptchaConfig { @Bean public Producer kaptchaProducer() { DefaultKaptcha kaptcha = new DefaultKaptcha(); Properties properties = new Properties(); properties.setProperty( "kaptcha.image.width" , "100" ); //图片宽度 properties.setProperty( "kaptcha.image.height" , "40" ); //图片高度 properties.setProperty( "kaptcha.textproducer.font.size" , "32" ); //字体大小 properties.setProperty( "kaptcha.textproducer.font.color" , "0,0,0" ); //字体颜色 properties.setProperty( "kaptcha.textproducer.char.string" , "0l23456789ABCDEFGHIJKLMNOPQRSGUVWXYZ" ); //随机字符串 properties.setProperty( "kaptcha.textproducer.char.length" , "4" ); //生成几个随机字符 properties.setProperty( "kaptcha.noise.impl" , "com.google.code.kaptcha.impl.DefaultNoise" ); //生成几个干扰 Config config = new Config(properties); kaptcha.setConfig(config); return kaptcha; } } |
生成验证码
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 | @Controller public class LoginController{ @Autowired private Producer kaptchaProducer; @RequestMapping (value = "/kaptcha" , method = RequestMethod.GET) public void getKaptcha(HttpServletResponse response, HttpSession session) { //生成验证码 String text = kaptchaProducer.createText(); BufferedImage image = kaptchaProducer.createImage(text); //将验证码存入session session.setAttribute( "kaptcha" , text); //将图片输出给浏览器 response.setContentType( "image/png" ); try { OutputStream outputStream = response.getOutputStream(); ImageIO.write(image, "png" , outputStream); } catch (IOException e) { logger.error( "响应验证码失败:" + e.getMessage()); } } } |
页面显示,使用的为Thymeleaf模板引擎
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <! DOCTYPE html> < html lang="en" xmlns:th="http://www.thymeleaf.org"> < head > < meta charset="UTF-8"> < title >登陆</ title > </ head > < body > < div > 验证码:< input type="text" placeholder="请输入验证码!"> < img th:src="@{/kaptcha}" id="kaptcha"/>< a href="javascript:refresh_kaptcha()">刷新验证码</ a > </ div > < script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></ script > < script > function refresh_kaptcha() { var path = "/community/kaptcha?p=" + Math.random(); $("#kaptcha").attr("src", path); } </ script > </ body > </ html > |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗