最近看到一个使用kaptcha实现验证码的案例,因此记录一下
1.创建一个Springboot项目,在pom.xml里面导入如下依赖
<dependency><groupId>com.github.penggle</groupId><artifactId>kaptcha</artifactId><version>2.3.2</version></dependency>
2.新建一个Config包,在包下编写如下配置类
@Configuration
public class KaptchaConfig {@Beanpublic Producer kaptchaProducer(){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","black");properties.setProperty("kaptcha.textproducer.char.string","0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");// 截取4个字符properties.setProperty("kaptcha.textproducer.char.length","4");// 设置图像干扰,防止机器人暴力破解properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");DefaultKaptcha kaptcha = new DefaultKaptcha();Config config = new Config(properties);kaptcha.setConfig(config);return kaptcha;}
3.编写一个Controller,使用如下代码实现在浏览器加载验证码
// 生成验证码@GetMapping("/kaptcha")public void getKaptcha(HttpServletResponse response, HttpSession session){// 生成验证码String text = kaptchaProduer.createText();// 生成图片BufferedImage image = kaptchaProduer.createImage(text);// 将验证码存入Sessionsession.setAttribute("kaptcha",text);//将图片输出给浏览器try {response.setContentType("image/png");OutputStream os = response.getOutputStream();ImageIO.write(image,"png",os);} catch (IOException e) {logger.error("响应验证码失败"+e.getMessage());}}
4.使用thymeleaf模板来加载验证码
<div class="form-group row mt-4"><label for="verifycode" class="col-sm-2 col-form-label text-right">验证码:</label><div class="col-sm-6"><input type="text" th:class="|form-control ${codeMsg!=null?'is-invalid':''}|" name="code" id="verifycode" placeholder="请输入验证码!"><div class="invalid-feedback" th:text="${codeMsg}">验证码不正确!</div></div><div class="col-sm-4"><img th:src="@{/kaptcha}" id="kaptcha" style="width:100px;height:40px;" class="mr-2"/><a href="javascript:refresh_kaptcha();" class="font-size-12 align-bottom">刷新验证码</a></div></div><script th:src="@{/js/jquery-3.3.1.min.js}" crossorigin="anonymous"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" crossorigin="anonymous"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" crossorigin="anonymous"></script><script th:src="@{/js/global.js}"></script><script>function refresh_kaptcha() {let path = "/kaptcha?p="+ Math.random();$("#kaptcha").attr("src",path);}</script>
效果如下