1.导入依赖
- 直接上官网即可,如下图
2.编写kaptcha配置类
- 编写KaptchaConfig类进行配置
- 代码:
package com.nowcoder.community.config;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
/**
* @author : wys
* @date : 2020-11-22 13:15
**/
@Configuration
public class KaptchaConfig {
@Bean
public Producer kaptchaProducer() {
//进行验证码的配置
Properties properties = new Properties();
//宽度
properties.setProperty("kaptcha.image.width","100");
//高度
properties.setProperty("kaptcha.image.height","40");
//里面元素的大小
properties.setProperty("kaptcha.textproducer.font.size","32");
//颜色
properties.setProperty("kaptcha.textproducer.font.color","0,0,0");
//会在哪些字符串选取验证码
properties.setProperty("kaptcha.textproducer.char.string","0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
//验证码字符个数
properties.setProperty("kaptcha.textproducer.char.length","4");
//验证码的干扰项
properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");
//声明配置
DefaultKaptcha kaptcha = new DefaultKaptcha();
Config config = new Config(properties);
kaptcha.setConfig(config);
return kaptcha;
}
}
3.在对应的LoginController中增加使用的方法
@RequestMapping(path = "/kaptcha", method = RequestMethod.GET)
public void getKaptcha(HttpServletResponse response, HttpSession session){
// 生成验证码
String text = kaptchaProducer.createText();
BufferedImage image = kaptchaProducer.createImage(text);
// 将验证码存入session
session.setAttribute("kaptcha", image);
// 将图片输出给浏览器
response.setContentType("image/png");
try {
OutputStream os = response.getOutputStream();
ImageIO.write(image, "png", os);
} catch (IOException e) {
logger.error("响应验证码失败:" + e.getMessage());
}
}
4.修改对应的前端代码
<div class="col-sm-4">
<img th:src="@{/kaptcha}" id="kaptcha" style="width:100px;height:40px;" class="mr-2"/>
<a href="javascript:refresh_kaptcha();" class="font-size-12 align-bottom">刷新验证码</a>
</div>
//js代码,实现刷新验证码的功能
<script>
function refresh_kaptcha() {
var path = CONTEXT_PATH + "/kaptcha?p=" + Math.random();
$("#kaptcha").attr("src", path);
}
</script>
5.实现效果图
-
第一张为可以直接访问路径时不断刷新,就可以产生不同的验证码图片
-
完全实现后的效果图,每次都可以点击刷新