1.主要依赖
<dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
2.配置类
/** * 生成验证码的配置 */ @Configuration public class CaptchaConfig { @Bean public Producer CaptchaProducer() { 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", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); //设置验证码的长度 properties.setProperty("kaptcha.textproducer.char.length", "4"); //设置添加噪声与否 properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise"); //将配置装载到一个实例中 DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); //将配置传入实例 defaultKaptcha.setConfig(new Config(properties)); return defaultKaptcha; }
2.控制器
@RestController @Api("用户接口") public class UserController {@GetMapping(Urls.User.CAPTCHA) @ApiOperation("请求一个验证码") public void getCaptcha(HttpServletResponse response, HttpSession session) { // 生成验证码 String text = captchaProducer.createText(); // 生成验证码图片 BufferedImage image = captchaProducer.createImage(text); // 将图片传入session session.setAttribute("captcha", text); // 将图片输出到前端(图片+格式) response.setContentType("image/png"); try { ServletOutputStream outputStream = response.getOutputStream(); ImageIO.write(image, "png", outputStream); } catch (IOException e) { e.printStackTrace(); System.out.println("响应验证码失败"); } }}
3.效果