SpringBoot集成Kaptcha实现登录获取验证码
2022-11-06 15:47 阿方技术圈 阅读(9) 评论(0) 收藏 举报1、首先添加依赖
<!--kaptcha验证码-->
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
2、编写Kaptcha的配置类
package com.louis.mango.config; import com.google.code.kaptcha.impl.DefaultKaptcha; import com.google.code.kaptcha.util.Config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Properties; @Configuration public class KaptchaConfig { @Bean public DefaultKaptcha producer(){ Properties properties = new Properties(); properties.put("kaptcha.border","no"); properties.put("kaptcha.textproducer.font.color","black"); properties.put("kaptcha.text.char.space","5"); Config config = new Config(properties); DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); defaultKaptcha.setConfig(config); return defaultKaptcha; } }
测试类
package com.louis.mango.controller; import com.google.code.kaptcha.Constants; import com.google.code.kaptcha.Producer; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.IOException; @RestController public class SysLoginController { @Autowired private Producer producer; @GetMapping("captcha.jpg") public void captcha(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException { response.setHeader("Cache-Controll","no-store,no-cache"); response.setContentType("image/jpeg"); //生成文字验证码 String text = producer.createText(); //生成图片验证码 BufferedImage image = producer.createImage(text); //保存验证码到session request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,text); ServletOutputStream out = response.getOutputStream(); ImageIO.write(image,"jpg",out); IOUtils.closeQuietly(out); } }
测试结果

浙公网安备 33010602011771号