1.SpringBoot整合kaptcha快速实现验证码功能
- 搭建基础SpringBoot环境,导入kaptcha依赖
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
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 KaptchaConfig {
@Bean(name = "defaultKaptcha")
public DefaultKaptcha defaultKaptcha(){
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
Properties properties = new Properties();
properties.setProperty("kaptcha.border","yes");
properties.setProperty("kaptcha.border.color","105,179,90");
properties.setProperty("kaptcha.textproducer.font.color","blue");
properties.setProperty("kaptcha.image.width","125");
properties.setProperty("kaptcha.image.height","45");
properties.setProperty("kaptcha.textproducer.font.size","45");
properties.setProperty("kaptcha.session.key","code");
properties.setProperty("kaptcha.textproducer.char.length","4");
properties.setProperty("kaptcha.textproducer.font.names","宋体,楷体,微软雅黑");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.wpq.ip.IpUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
@Controller
public class TestController {
@Resource
private DefaultKaptcha defaultKaptcha;
@GetMapping("/kaptcha.jpg")
public void getKaptcha(HttpServletRequest request, HttpServletResponse response){
String ipAddr = IpUtils.getIpAddr(request);
response.setHeader("Cache-Control","no-store,no-cache");
response.setContentType("image/jpg");
String kaptchaText = defaultKaptcha.createText();
BufferedImage image = defaultKaptcha.createImage(kaptchaText);
try {
ImageIO.write(image,"jpg",response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 本服务器或其它服务器使用标签绑定此生成验证码接口,即可拿到验证码图片
<img src="http://localhost:8080/kaptcha.jpg" />
- 不使用HttpServletResponse的输出流,使用AJAX异步调用返回结果方式
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.wpq.ip.IpUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Encoder;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@Controller
@CrossOrigin(allowedHeaders = "*")
public class TestController {
@Resource
private DefaultKaptcha defaultKaptcha;
@Resource
private RedisCache redisCache;
private static final String KAPTCHA_PREFIX="kaptcha";
private static final String KAPTCHA_SPLITTER="::";
@ResponseBody
@GetMapping("/kaptcha.jpg")
public Map<String,Object> getKaptcha(HttpServletRequest request){
StringBuilder sb = new StringBuilder();
String cacheKey = sb.append(KAPTCHA_PREFIX)
.append(KAPTCHA_SPLITTER)
.append(this.uuid()).toString();
String kaptchaText = defaultKaptcha.createText();
redisCache.set(cacheKey, kaptchaText, 3, TimeUnit.MINUTES);
BufferedImage image = defaultKaptcha.createImage(kaptchaText);
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
try {
ImageIO.write(image,"jpg",byteStream);
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
Map<String,Object> data = new HashMap<String, Object>();
data.put("cacheKey",cacheKey);
data.put("img", encoder.encode(byteStream.toByteArray()));
return data;
}
public String uuid(){
return UUID.randomUUID().toString().replace("-","");
}
}
- 前端页面的img标签使用data URL的形式获取验证码:“data:image/gif;base64,”+BASE64编码后的图片数据
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>
<img id="img" src="" /><br>
<span id="cacheKey"></span>
<input type="button" value="获取验证码" onclick="getCode();">
</p>
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script>
function getCode() {
$.ajax({
url:"http://localhost:8080/kaptcha.jpg",
dataType:"json",
type:"get",
success:function (r) {
alert(JSON.stringify(r));
$("#img")[0].src = "data:image/gif;base64,"+r.img;
$("#cacheKey").text(r.cacheKey);
}
})
}
</script>
</body>
</html>
- 效果展示