效果圖
點擊會切換驗證碼的一個效果
前端頁面
這里用的是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(); } }