效果图
点击会切换验证码的一个效果
前端页面
这里用的是thymeleaf
后端实现
导入pom依赖
<!-- 验证码 --> <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
创建kaptcha配置类
import com.google.code.kaptcha.impl.DefaultKaptcha; import com.google.code.kaptcha.util.Config; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import java.util.Properties; @Component public class KaptchaConfig { @Bean public DefaultKaptcha getDefaultKaptcha() { DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); Properties properties = new Properties(); properties.put("kaptcha.border", "no"); properties.put("kaptcha.textproducer.font.color", "black"); properties.put("kaptcha.image.width", "150"); properties.put("kaptcha.image.height", "40"); properties.put("kaptcha.textproducer.font.size", "30"); properties.put("kaptcha.session.key", "verifyCode"); //设置验证码字符数量 properties.put("kaptcha.textproducer.char.space", "5"); Config config = new Config(properties); defaultKaptcha.setConfig(config); return defaultKaptcha; } }
创建接收验证码请求Controller
import com.google.code.kaptcha.impl.DefaultKaptcha; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; @Controller public class CommonController { @Autowired private DefaultKaptcha captchaProducer; @GetMapping("/common/kaptcha") public void defaultKapcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { byte[] captchaOutputStream = null; ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream(); try { //生产验证码字符串并保存到session中 String verifyCode = captchaProducer.createText(); httpServletRequest.getSession().setAttribute("verifyCode", verifyCode); //根据验证码字符创建图片 BufferedImage challenge = captchaProducer.createImage(verifyCode); //图片写入 ImageIO.write(challenge, "jpg", imgOutputStream); } catch (IllegalArgumentException e) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } captchaOutputStream = imgOutputStream.toByteArray(); httpServletResponse.setHeader("Cache-Control", "no-store"); httpServletResponse.setHeader("Pragma", "no-cache"); httpServletResponse.setDateHeader("Expires", 0); httpServletResponse.setContentType("image/jpeg"); ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream(); responseOutputStream.write(captchaOutputStream); responseOutputStream.flush(); responseOutputStream.close(); } }