Java 生成驗證碼 可自定義配置

1.使用kaptcha配置生成驗證碼

使用maven座標引入pom

<dependency>
 <groupId>com.github.penggle</groupId>
 <artifactId>kaptcha</artifactId>
 <version>2.3.2</version>
 <exclusions>
 <exclusion>
 <artifactId>javax.servlet-api</artifactId>
 <groupId>javax.servlet</groupId>
 </exclusion>
 </exclusions>
</dependency>

 

新建配置文件kaptcha.properties,下面的驗證碼配置,從英文單詞的角度很容易理解,當我們需要調整驗證碼的邊框、顏色、大小、字體等屬性的時候,可以修改這些配置。

kaptcha.border=no
kaptcha.border.color=105,179,90
kaptcha.image.width=200
kaptcha.image.height=60
kaptcha.session.key=code
kaptcha.textproducer.font.color=blue
kaptcha.textproducer.font.size=35
kaptcha.textproducer.char.length=4
kaptcha.textproducer.font.names=宋體,楷體,微軟雅黑

 

新建配置類CaptchaConfig加載配置文件

@Component
@PropertySource(value = {"classpath:kaptcha.properties"})
public class CaptchaConfig {

 @Value("${kaptcha.border}")
 private String border;
    @Value("${kaptcha.border.color}")
 private String borderColor;
    @Value("${kaptcha.textproducer.font.color}")
 private String fontColor;
    @Value("${kaptcha.image.width}")
 private String imageWidth;
    @Value("${kaptcha.image.height}")
 private String imageHeight;
    @Value("${kaptcha.session.key}")
 private String sessionKey;
    @Value("${kaptcha.textproducer.char.length}")
 private String charLength;
    @Value("${kaptcha.textproducer.font.names}")
 private String fontNames;
    @Value("${kaptcha.textproducer.font.size}")
 private String fontSize;

    @Bean(name = "captchaProducer")
 public DefaultKaptcha getKaptchaBean() {
 DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", border);
        properties.setProperty("kaptcha.border.color", borderColor);
        properties.setProperty("kaptcha.textproducer.font.color", fontColor);
        properties.setProperty("kaptcha.image.width", imageWidth);
        properties.setProperty("kaptcha.image.height", imageHeight);
        properties.setProperty("kaptcha.session.key", sessionKey);
        properties.setProperty("kaptcha.textproducer.char.length", charLength);
        properties.setProperty("kaptcha.textproducer.font.names", fontNames);
        properties.setProperty("kaptcha.textproducer.font.size",fontSize);
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }

}

至此,Kaptcha開源驗證碼軟件的配置我們就完成了。

 

2.生成驗證碼並保存

 通過captchaProducer.createText()生成驗證碼文字,並和失效時間一起保存到CaptchaImageVO中。

將CaptchaImageVO驗證碼信息類對象,保存到session中。

通過captchaProducer.createImage(capText)生成驗證碼圖片,並通過ServletOutputStream返回給前端

 

@RestController
public class CaptchaController {

 @Resource
 DefaultKaptcha captchaProducer;

    /**
 * 獲取驗證碼
 */
 @GetMapping("kaptcha")
 public void kaptcha(HttpSession session, HttpServletResponse response) throws Exception {

 response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        String capText = captchaProducer.createText();
        CaptchaImageVO captchaImageVO = new CaptchaImageVO(capText,2 * 60);
        //將驗證碼存到session
 session.setAttribute(Constants.KAPTCHA_SESSION_KEY, captchaImageVO);

        //將圖片返回給前端
 try(ServletOutputStream out = response.getOutputStream();) {
 BufferedImage bi = captchaProducer.createImage(capText);
            ImageIO.write(bi, "jpg", out);
            out.flush();
        }//使用try-with-resources不用手動關閉流
 }

}

 


 
CaptchaImageVO實體類: 
@Data
public class CaptchaImageVO {

 //驗證碼文字
 private String code;
    //驗證碼失效時間
 private LocalDateTime expireTime;

    public CaptchaImageVO(String code, int expireAfterSeconds){
 this.code = code;
        this.expireTime = LocalDateTime.now().plusSeconds(expireAfterSeconds);
    }

 //驗證碼是否失效
 public boolean isExpried() {
 return LocalDateTime.now().isAfter(expireTime);
    }

}

 

3.測試

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
 <script th:inline="javascript">
 var url_image = [[@{/kaptcha}]];
 </script>
</head>
<body>
 <img th:src="@{/kaptcha}" id="kaptcha" width="110px" height="40px"/>
</body>
<script th:inline="javascript">
 window.onload=function(){
 var kaptchaImg = document.getElementById("kaptcha");
        kaptchaImg.onclick = function(){
 kaptchaImg.src = url_image + "?" + Math.floor(Math.random() * 100);
        }
 }
</script>
</html>

 

實現的效果是,頁面初始化即加載驗證碼。以後每一次點擊,都會更新驗證碼。

 

 

4.kaptcha配置項

Constant 描述 默認值
kaptcha.border 圖片邊框,合法值:yes , no yes
kaptcha.border.color 邊框顏色,合法值: r,g,b (and optional alpha) 或者 white,black,blue. black
kaptcha.image.width 圖片寬 200
kaptcha.image.height 圖片高 50
kaptcha.producer.impl 圖片實現類 com.google.code.kaptcha.impl.DefaultKaptcha
kaptcha.textproducer.impl 文本實現類 com.google.code.kaptcha.text.impl.DefaultTextCreator
kaptcha.textproducer.char.string 文本集合,驗證碼值從此集合中獲取 abcde2345678gfynmnpwx
kaptcha.textproducer.char.length 驗證碼長度 5
kaptcha.textproducer.font.names 字體 Arial, Courier
kaptcha.textproducer.font.size 字體大小 40px.
kaptcha.textproducer.font.color 字體顏色,合法值: r,g,b 或者 white,black,blue. black
kaptcha.textproducer.char.space 文字間隔 2
kaptcha.noise.impl 干擾實現類 com.google.code.kaptcha.impl.DefaultNoise
kaptcha.noise.color 干擾 顏色,合法值: r,g,b 或者 white,black,blue. black
kaptcha.background.impl 背景實現類 com.google.code.kaptcha.impl.DefaultBackground
kaptcha.background.clear.from 背景顏色漸變,開始顏色 light grey
kaptcha.background.clear.to 背景顏色漸變, 結束顏色 white
kaptcha.word.impl 文字渲染器 com.google.code.kaptcha.text.impl.DefaultWordRenderer
kaptcha.session.key session key KAPTCHA_SESSION_KEY
kaptcha.session.date session date KAPTCHA_SESSION_DATE
kaptcha.obscurificator.impl

圖片樣式:<br />水紋 com.google.code.kaptcha.impl.WaterRipple

<br /> 魚眼 com.google.code.kaptcha.impl.FishEyeGimpy

<br /> 陰影 com.google.code.kaptcha.impl.ShadowGimpy

com.google.code.kaptcha.impl.WaterRipple


 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章