Spring Boot集成kaptcha验证码的使用
本文主要在Spring Boot中使用kaptcha验证码,使用的是默认的样式
Maven依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>kaptcha-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
验证码组件
import com.baomidou.kaptcha.Kaptcha;
import com.baomidou.kaptcha.exception.KaptchaRenderException;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* 验证码组件
*
* @author cc
*/
@Component
public class GoogleOverrideKaptcha implements Kaptcha {
private DefaultKaptcha kaptcha;
public GoogleOverrideKaptcha(DefaultKaptcha kaptcha) {
this.kaptcha = kaptcha;
}
public String render(HttpServletRequest request) {
//生成验证码文本
String sessionCode = kaptcha.createText();
ByteArrayOutputStream outputStream = null;
try {
//放入缓存中
HttpSession session = request.getSession();
session.setAttribute("verificationCode",sessionCode);
System.out.println(sessionCode);
outputStream = new ByteArrayOutputStream();
ImageIO.write(kaptcha.createImage(sessionCode), "jpg", outputStream);
BASE64Encoder encoder = new BASE64Encoder();
String base64 = encoder.encode(outputStream.toByteArray());
String captchaBase64 = "data:image/jpeg;base64," + base64.replaceAll("\r\n", "").replaceAll("\n","").replace("\r","");
return captchaBase64;
} catch (IOException e) {
throw new KaptchaRenderException(e);
}finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public String render() {
return null;
}
@Override
public boolean validate(String code) {
return validate(code, 900);
}
@Override
public boolean validate(String s, long l) {
return false;
}
}
自定义样式
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.google.code.kaptcha.util.Config;
import java.util.Properties;
/**
* @author cc
* 验证码bean
*/
@Configuration
public class CaptchaConfig {
@Bean
public DefaultKaptcha getKaptchaBean() {
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.obscurificator.impl", "com.google.code.kaptcha.impl.WaterRipple");
properties.setProperty("kaptcha.producer.impl", "com.google.code.kaptcha.impl.DefaultKaptcha");
properties.setProperty("kaptcha.textproducer.char.space", "2");
properties.setProperty("kaptcha.image.width", "100");
properties.setProperty("kaptcha.image.height", "34");
properties.setProperty("kaptcha.session.key", "code");
properties.setProperty("kaptcha.textproducer.char.length", "4");
properties.setProperty("kaptcha.textproducer.font.names", " 宋体,楷体,微软雅黑");
properties.setProperty("kaptcha.textproducer.font.size", "24");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
样式参数
kaptcha.border 图片边框,合法值:yes , no yes
kaptcha.border.color 边框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue. black
kaptcha.border.thickness 边框厚度,合法值:>0 1
kaptcha.image.width 图片宽 200
kaptcha.image.height 图片高 50
kaptcha.producer.impl 图片实现类 com.google.code.kaptcha.impl.DefaultKaptcha
kaptcha.textproducer.impl 文本实现类 com.google.code.kaptcha.text.impl.DefaultTextCreator
kaptcha.textproducer.char.string 文本集合,验证码值从此集合中获取 abcde2345678gfynmnpwx
kaptcha.textproducer.char.length 验证码长度 5
kaptcha.textproducer.font.names 字体 Arial, Courier
kaptcha.textproducer.font.size 字体大小 40px
kaptcha.textproducer.font.color 字体颜色,合法值: r,g,b 或者 white,black,blue. black
kaptcha.textproducer.char.space 文字间隔 2
kaptcha.noise.impl 干扰实现类 com.google.code.kaptcha.impl.DefaultNoise
kaptcha.noise.color 干扰颜色,合法值: r,g,b 或者 white,black,blue. black
kaptcha.obscurificator.impl 图片样式:水纹com.google.code.kaptcha.impl.WaterRipple
鱼眼com.google.code.kaptcha.impl.FishEyeGimpy
阴影com.google.code.kaptcha.impl.ShadowGimpy com.google.code.kaptcha.impl.WaterRipple
kaptcha.background.impl 背景实现类 com.google.code.kaptcha.impl.DefaultBackground
kaptcha.background.clear.from 背景颜色渐变,开始颜色 light grey
kaptcha.background.clear.to 背景颜色渐变,结束颜色 white
kaptcha.word.impl 文字渲染器 com.google.code.kaptcha.text.impl.DefaultWordRenderer
kaptcha.session.key session key KAPTCHA_SESSION_KEY
kaptcha.session.date session date KAPTCHA_SESSION_DATE
Controller调用
*[HTML]:java
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* 验证码-controller
*
* @author cc
*/
@Controller
@RequestMapping("wsd/loginCode")
public class FrmLoginCodeControl{
@Autowired
private GoogleOverrideKaptcha overrideKaptcha;
@Autowired
private DefaultKaptcha captchaProducer;
/**
* 生成验证码
* @param request
*/
@ResponseBody
@RequestMapping(value="/verificationCode")
public Map<String,Object> outputCaptcha(HttpServletRequest request) {
Map<String, Object> map = new HashMap<>();
String captchaBase64 = overrideKaptcha.render(request);
map.put("imgBase64", captchaBase64);
return map;
}
}
前台调用
<div class="login-main-content-row row3 clearfix" style="margin-top: 40px;float: left;margin-left: 43px;">
<input type="text" id="loginCode" autocomplete="off" style="font-size:24px;color: #a1d8ff;float: left;width: 80%;margin-left: -45px;"
name="loginCode" placeholder="验证码" />
<div style="float: right;margin-top: -8px;"><img id="codeImg" style="height: 34px;width: 100px;" src=""/></div>
</div>
$(document).ready(function() {
changeCode();
$("#codeImg").bind("click", changeCode);
});
function genTimestamp() {
var time = new Date();
return time.getTime();
}
function changeCode() {
$.ajax({
url:"wsd/loginCode/verificationCode?t=" + genTimestamp(),
dataType : "json",
async : false,
success:function(data){
$("#codeImg").attr("src", data.imgBase64);
}
});
}
效果
[添加链接描述](https://www.cclzz.cn)