1. 首先,我们在pom.xml文件中引入kaptcha的maven依赖。
1 <dependency> 2 <groupId>com.github.penggle</groupId> 3 <artifactId>kaptcha</artifactId> 4 <version>2.3.2</version> 5 </dependency>
2. 然后,我们编写kaptcha的配置类:KaptchaConfig.java。
1 package com.rqfreefly.community.config; 2 3 import com.google.code.kaptcha.Producer; 4 import com.google.code.kaptcha.impl.DefaultKaptcha; 5 import com.google.code.kaptcha.util.Config; 6 import org.springframework.context.annotation.Bean; 7 import org.springframework.context.annotation.Configuration; 8 9 import java.util.Properties; 10 11 @Configuration 12 public class KaptchaConfig { 13 14 @Bean 15 public Producer kaptchaProducer() { 16 Properties properties = new Properties(); 17 properties.setProperty("kaptcha.image.width", "100"); 18 properties.setProperty("kaptcha.image.height", "40"); 19 properties.setProperty("kaptcha.textproducer.font.size", "32"); 20 properties.setProperty("kaptcha.textproducer.font.color", "0,0,0"); 21 properties.setProperty("kaptcha.textproducer.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYAZ"); 22 properties.setProperty("kaptcha.textproducer.char.length", "4"); 23 properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise"); 24 25 DefaultKaptcha kaptcha = new DefaultKaptcha(); 26 Config config = new Config(properties); 27 kaptcha.setConfig(config); 28 return kaptcha; 29 } 30 31 }
3. 接下来,我们编写kaptcha的控制层。
1 @RequestMapping(path = "/kaptcha", method = RequestMethod.GET) 2 public void getKaptcha(HttpServletResponse response, HttpSession session) { 3 String text = kaptchaProducer.createText(); 4 BufferedImage image = kaptchaProducer.createImage(text); 5 session.setAttribute("kaptcha", text); 6 response.setContentType("image/png"); 7 try { 8 ServletOutputStream os = response.getOutputStream(); 9 ImageIO.write(image, "png", os); 10 } catch (IOException e) { 11 logger.error("响应验证码失败:" + e.getMessage()); 12 } 13 }
4. 然后,我们就可以在前端调用katpcha的接口生成验证码。
标签:SpringBoot,Kaptcha,image,验证码,kaptcha,setProperty,import,com,properties From: https://www.cnblogs.com/RQfreefly/p/17177095.html