滿足你,先看效果(樣式是可以自己定製的)
前端代碼示例
html
<!-- 驗證碼 -->
<img class="loginCode" src="/login/kaptcha" />
JavaScript(點擊時刷新驗證碼)
(function (window,document) {
//給路徑加一個參數,讓瀏覽器誤以爲路徑變了,會重新請求
$('.loginCode').click(function () {
this.src = "/login/kaptcha?d="+ new Date();
})
})(window,document)
後端代碼配置和代碼示例
有Maven的同學,可以在pom.xml配置(沒有也沒關係,下面給你準備好了jar導入即可)
<!--驗證碼-->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
關注微信公衆號“一顆剽悍的種子”,輸入“編程資源”獲取jar包
Config 代碼配置驗證碼屬性
@Bean
public Producer getKaptcha(){
DefaultKaptcha kaptcha = new DefaultKaptcha();
Properties properties = new Properties();
Config config = new Config(properties);
//設置圖片邊框
properties.setProperty("kaptcha.border", "yes");
//設置邊框顏色只支持RGB和英文單詞顏色
properties.setProperty("kaptcha.border.color", "75,139,244");
//設置字體顏色只支持RGB和英文單詞顏色
properties.setProperty("kaptcha.textproducer.font.color", "75,139,244");
//設置圖片寬
properties.setProperty("kaptcha.image.width","100");
//設置圖片高
properties.setProperty("kaptcha.image.height","40");
//設置字體大小
properties.setProperty("kaptcha.image.font.size","20");
//設置驗證碼長度
properties.setProperty("kaptcha.textproducer.char.length","4");
//設置取消干擾
properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");
kaptcha.setConfig(config);
return kaptcha;
}
}
Controller 請求時輸出驗證碼
@RequestMapping(path = "kaptcha", method = RequestMethod.GET)
public void getKaptcha(HttpServletResponse response, HttpSession session) {
String text = kaptcha.createText();
BufferedImage image = kaptcha.createImage(text);
/**
* 驗證碼屬於敏感信息,所以存在session中
*/
session.setAttribute("kaptcha", text);
//圖片輸出給瀏覽器
response.setContentType("image/png");
try {
OutputStream out = response.getOutputStream();
ImageIO.write(image, "png", out);
} catch (IOException e) {
logger.error("驗證碼失敗:" + e.getMessage());
}
}
我是一顆剽悍的種子,一顆偏愛前端的後端新司機。 把我會的認真的分享——一直是我寫博客的信條,把文章的代碼帶走,你的四連留下,點贊、收藏、評論、關注是我寫博客的最大動力