java 生成驗證碼
阿新 • • 發佈:2020-12-10
1.引入maven依賴
<dependency> <groupId>com.github.axet</groupId> <artifactId>kaptcha</artifactId> <version>0.0.9</version> </dependency>
2.配置屬性
@Configuration public class VerifyCodeConfig { @Bean public DefaultKaptcha producer() { Properties properties = new Properties(); properties.put("kaptcha.border", "yes");//是否有邊框 properties.put("kaptcha.textproducer.font.color", "blue");//背景顏色 properties.put("kaptcha.textproducer.char.space", "6");//字元數量 properties.put("kaptcha.textproducer.font.names", "Arial,Courier,cmr10,宋體,楷體,微軟雅黑");//字型 Config config = new Config(properties); DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); defaultKaptcha.setConfig(config); return defaultKaptcha; } }
3.建立一個contoller:
@Controller public class ThymeleafController { @Autowired private Producer producer; @GetMapping("/get/verification/code") public void VerificationCode(HttpServletResponse response){ response.setHeader("Cache-Control", "no-store, no-cache"); response.setContentType("image/jpeg"); String text = producer.createText(); //驗證碼內容可以儲存資料庫,並設定過期時間 BufferedImage image = producer.createImage(text); ServletOutputStream out=null; try { out= response.getOutputStream(); ImageIO.write(image, "jpg", out); }catch (Exception ex){if(null!=out){ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
4.瀏覽器訪問: