1.引入pom
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
2.编写配置类(KaptchaConfig)
@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","black");
//字符范围
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.编写get请求(controller层)
@GetMapping("/kaptcha")
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="form-group row mt-4">
<label for="verifycode" class="col-sm-2 col-form-label text-right">验证码:</label>
<div class="col-sm-6">
<input type="text" class="form-control is-invalid" id="verifycode" placeholder="请输入验证码!">
<div class="invalid-feedback">
验证码不正确!
</div>
</div>
<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>
</div>
5.编写js实现点击动态刷新
<script>
function refresh_kaptcha(){
const path = CONTEXT_PATH + "/kaptcha?P=" + Math.random();
$("#kaptcha").attr("src",path);
}
</script>
将请求路径拼接后随机填入数字,get请求不变,防止浏览器默认请求未变化造成刷新失败
点击看gitee源码!