SpringBoot使用kaptcha验证码

小鱼儿 2022-05-27 03:29 364阅读 0赞

在pom.xml配置

  1. <!-- 验证码 -->
  2. <dependency>
  3. <groupId>com.github.axet</groupId>
  4. <artifactId>kaptcha</artifactId>
  5. <version>0.0.9</version>
  6. </dependency>

配置kaptcha

  1. package gm.config;
  2. import com.google.code.kaptcha.impl.DefaultKaptcha;
  3. import com.google.code.kaptcha.util.Config;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import java.util.Properties;
  7. /** * 生成验证码配置 */
  8. @Configuration
  9. public class KaptchaConfig {
  10. @Bean
  11. public DefaultKaptcha producer() {
  12. Properties properties = new Properties();
  13. properties.put("kaptcha.border", "no");
  14. properties.put("kaptcha.textproducer.font.color", "black");
  15. properties.put("kaptcha.textproducer.char.space", "5");
  16. Config config = new Config(properties);
  17. DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
  18. defaultKaptcha.setConfig(config);
  19. return defaultKaptcha;
  20. }
  21. }

前端视图的src链接处理,生成验证码

  1. // 获取验证码
  2. @GetMapping("/kaptcha")
  3. public void kaptcha(HttpServletResponse response, HttpServletRequest request) throws Exception {
  4. response.setHeader("Cache-Control", "no-store, no-cache");
  5. response.setContentType("image/jpeg");
  6. String text = defaultKaptcha.createText();
  7. BufferedImage image = defaultKaptcha.createImage(text);
  8. request.getSession().setAttribute("code", text);
  9. ServletOutputStream out = response.getOutputStream();
  10. ImageIO.write(image, "jpg", out);
  11. out.close();
  12. }

发表评论

表情:
评论列表 (有 0 条评论,364人围观)

还没有评论,来说两句吧...

相关阅读