76 lines
2.2 KiB
Markdown
76 lines
2.2 KiB
Markdown
|
# 生成验证码
|
||
|
|
||
|
---
|
||
|
|
||
|
## 导入 Kaptcha 依赖
|
||
|
|
||
|
## 配置 Kaptcha
|
||
|
|
||
|
```java
|
||
|
@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.textproducer.noise.impl", "com.google.code.kaptcha.impl.NoNoise");
|
||
|
|
||
|
DefaultKaptcha kaptcha = new DefaultKaptcha();
|
||
|
Config config = new Config(properties);
|
||
|
kaptcha.setConfig(config);
|
||
|
return kaptcha;
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
```
|
||
|
|
||
|
## 生成随机字符、生成图片
|
||
|
|
||
|
|
||
|
|
||
|
```java
|
||
|
@GetMapping("/kaptcha")
|
||
|
public void getKaptcha(HttpServletResponse response, HttpSession session) {
|
||
|
// 生成验证码
|
||
|
String text = kaptchaProducer.createText(); // 生成随机字符
|
||
|
BufferedImage image = kaptchaProducer.createImage(text); // 生成图片
|
||
|
|
||
|
// 将验证码存入 session
|
||
|
session.setAttribute("kaptcha", text);
|
||
|
|
||
|
// 将图片输出给浏览器
|
||
|
response.setContentType("image/png");
|
||
|
try {
|
||
|
ServletOutputStream os = response.getOutputStream();
|
||
|
ImageIO.write(image, "png", os);
|
||
|
} catch (IOException e) {
|
||
|
logger.error("响应验证码失败", e.getMessage());
|
||
|
}
|
||
|
}
|
||
|
```
|
||
|
|
||
|
|
||
|
|
||
|
```js
|
||
|
<img th:src="@{/kaptcha}" id = "kaptcha"/>
|
||
|
<a href="javascript:refresh_kaptcha();">刷新验证码</a>
|
||
|
|
||
|
<script>
|
||
|
function refresh_kaptcha() {
|
||
|
var path = CONTEXT_PATH + "/kaptcha?p=" + Math.random();
|
||
|
$("#kaptcha").attr("src", path);
|
||
|
}
|
||
|
</script>
|
||
|
```
|
||
|
|
||
|
浏览器看到路径变了就会自动请求服务器,即请求 getKaptcha 方法。这个 p 参数只是我们用来改变 url 的(因为有些浏览器比较智能,看见 url 没变就不会重新请求服务器),并不需要在服务端使用它
|