利用kaptcha生成验证码:
Kaptcha 是一个可高度配置的实用验证码生成工具。
可自由配置的选项如:
验证码的字体
验证码字体的大小
验证码字体的字体颜色
验证码内容的范围(数字,字母,中文汉字!)
验证码图片的大小,边框,边框粗细,边框颜色
验证码的干扰线
验证码的样式(鱼眼样式、3D、普通模糊、…)
- 1.导入 jar 包
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
- 2.编写 Kaptcha 配置类
因为并没有整合进spring所以我们需要自己做整合,写一个配置类
package com.guo.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;
//@Configuration表明这是一个配置类
@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
@Autowired
private Producer kaptchaProducer;
private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
//生成验证码的方法
@RequestMapping(path = "/kaptcha",method = RequestMethod.GET)
/**
* HttpServletResponse:将图片输出回浏览器
* HttpSession:将生成的验证码存入session
*/
public void getKaptcha(HttpServletResponse response, HttpSession session){
//1. 生成验证码图片
//1.1 生成文字
String text = kaptchaProducer.createText();
//1.2 生成图片
BufferedImage image = kaptchaProducer.createImage(text);
//2. 将验证码存入session
session.setAttribute("kaptcha",text);
//3. 将图片返回给浏览器
response.setContentType("image/png");
try {
ServletOutputStream os = response.getOutputStream();
ImageIO.write(image,"png",os);
} catch (IOException e) {
logger.error("响应验证码失败"+e.getMessage());
}
}
login.html
<!--
th:src="@{/kaptcha}" 将验证码图片的链接转置kaptcha路径下
href="javascript:refresh_kaptcha();"
利用js编写刷新验证码的方法
-->
<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>
<script>
function refresh_kaptcha() {
//定义验证码路径,为了防止路径修改时的替换,直接引用global.js的CONTEXT_PATH
var path = CONTEXT_PATH + “/kaptcha”?p="+Math.random();
//将id="kaptcha"的src进行替换
$("#kaptcha").attr("src",path);
}
</script>
global.js
var CONTEXT_PATH = "/community"