利用 kaptcha 构建验证码
一、导入 jar 包
<!-- 验证码包 -->
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version> 0.0.9</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!--eacache-->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
二、配置 yml
cache:
ehcache:
config: classpath:/ehcache.xml
三、新建 ehcache.xml
在 resources 下新建 ehcache.xml 文件,并把以下内容导入进去
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<diskStore path="java.io.tmpdir"/>
<!--defaultCache:echcache的默认缓存策略 -->
<!--
缓存配置
diskStore:指定数据在磁盘中的存储位置。
name:缓存名称。
defaultCache:当借助CacheManager.add("demoCache")创建Cache时,EhCache便会采用<defalutCache/>指定的的管理策略,以下属性是必须的:
maxElementsInMemory:缓存最大个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
maxElementsOnDisk:硬盘最大缓存个数。
diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。
-->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<cache name="captchaCache"
maxElementsInMemory="1000000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</cache>
</ehcache>
四、在启动类上添加 @EnableCaching
注解
五、验证码配置
package com.livekeys.captcha.config;
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
public class CaptchaConfig {
@Bean
public DefaultKaptcha producer() {
Properties properties = new Properties();
properties.put("kaptcha.border", "no");
properties.put("kaptcha.textproducer.font.color", "black");
properties.put("kaptcha.textproducer.char.space", "5");
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
还有更多的配置可设置
properties.put("kaptcha.border","yes"); //是否需要外边框(yes,no)
properties.put("kaptcha.border.thickness","2"); //边框厚度,合法值:>0
properties.put("kaptcha.border.color","blue"); //框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue
properties.put("kaptcha.textproducer.font.color","black"); //字体颜色
properties.put("kaptcha.obscurificator.impl","com.google.code.kaptcha.impl.FishEyeGimpy"); //渲染效果:水纹:WaterRipple;鱼眼:FishEyeGimpy;阴影:ShadowGimpy
properties.put("kaptcha.noise.impl","com.google.code.kaptcha.impl.DefaultNoise"); //配置干扰线–噪点(只改变最后一个单词:NoNoise,DefaultNoise)
properties.put("kaptcha.noise.color","yellow"); //干扰 颜色,合法值: r,g,b 或者 white,black,blue.
properties.put("kaptcha.image.width","90"); // 设置宽度
properties.put("kaptcha.image.height","33"); // 设置高度
properties.put("kaptcha.textproducer.font.size","25"); // 设置字号
properties.put("kaptcha.textproducer.char.length","4"); //生成验证码的长度(也就是要几个字)
properties.put("kaptcha.textproducer.char.space","5"); //文字间隔
//和登录框背景颜色一致
//背景颜色渐变,开始颜色
properties.put("kaptcha.background.clear.from","247,247,247");
//背景颜色渐变, 结束颜色
properties.put("kaptcha.background.clear.to","247,247,247");
properties.put("kaptcha.word.impl","com.google.code.kaptcha.text.impl.DefaultWordRenderer");
六、Controller 层
package com.livekeys.captcha.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.code.kaptcha.Producer;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
@RestController
public class CaptchaController {
@Autowired
private Producer producer;
@Autowired
private CacheManager cacheManager;
@GetMapping("/captcha")
public void getCaptcha(HttpServletResponse response, HttpServletRequest request, @RequestParam("deviceId") String deviceId) throws IOException {
// 设置 response 禁止图像缓存
response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg");
// 生成文字验证码
String text = producer.createText();
// 生成图片验证码
BufferedImage image = producer.createImage(text);
// 保存到验证码到 session
Cache cache = cacheManager.getCache("captchaCache");
Element element = new Element(deviceId, text);
log.info("generateCaptcha:" + deviceId);
cache.put(element);
// 将验证码图片输出到前端
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "jpg", out);
// 关闭 out
try {
if (out != null) {
out.close();
}
} catch (IOException e) {}
}
}
七、前端
用于生成机器码的 js:Math.uuid.js (来源于网上)
(function() {
// Private array of chars to use
var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
Math.uuid = function (len, radix) {
var chars = CHARS, uuid = [], i;
radix = radix || chars.length;
if (len) {
// Compact form
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
} else {
// rfc4122, version 4 form
var r;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random()*16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
};
})();
获取验证码
<img id="captcha" name="captcha" src="" />
let uuid = Math.uuid();
(function getCaptcha() {
/* 图形验证码 */
var captchaUrl = "http://localhost:8080/captcha";
$('#captcha').click(function () {
this.src = captchaUrl + '?deviceId='+uuid+'&t=' + (new Date).getTime();
}).trigger('click');
})();
这样,页面上就可以获取验证码了