Spring Boot集成Kaptcha实现图片验证码

废话不多说,直接开始

首先,在pom.xml用引入Kaptcha依赖

<!-- 验证码 -->
	<dependency>
           <groupId>com.github.penggle</groupId>
           <artifactId>kaptcha</artifactId>
           <version>2.3.2</version>
    </dependency>

由于springBoot没有xml配置,是采用配置类来实现的自定义配置,所以创建一个自定义配置类,这个配置类就是用来定义验证码各自参数的:

//验证码配置类
@Component
public class KaptchaConfig {
	@Bean  
    public DefaultKaptcha getDefaultKaptcha(){  
        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", "green");//字体颜色
        properties.setProperty("kaptcha.noise.color", "0,255,255");  //干扰颜色
        properties.setProperty("kaptcha.image.width", "110");  //宽度
        properties.setProperty("kaptcha.image.height", "40");  //高度
        properties.setProperty("kaptcha.textproducer.font.size", "30"); //字体大小
        properties.setProperty("kaptcha.textproducer.char.space", "3"); //文字间距
        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;  
    }  
}

Kaptcha参数设置如下:

Constant描述默认值
kaptcha.border图片边框,合法值:yes , noyes
kaptcha.border.color边框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue.black
kaptcha.border.thickness边框厚度,合法值:>01
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.keysession keyKAPTCHA_SESSION_KEY
kaptcha.session.datesession dateKAPTCHA_SESSION_DATE

配置完成后,需要定义一个接口用来获取验证码图片的数据,然后把图片验证码的值保存在session中,在用户登录时,可以判断输入的验证码和session中的验证码是否相同。

/**
	 * 获取验证码 的 请求路径
	 * 
	 * @param httpServletRequest
	 * @param httpServletResponse
	 * @throws Exception
	 */
	@RequestMapping("/defaultKaptcha")
	@ApiOperation(value = "后台-获取图片验证码接口")
	public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
			throws Exception {
		byte[] captchaChallengeAsJpeg = null;
		ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
		try {
			// 生产验证码字符串并保存到session中
			String createText = captchaProducer.createText();
			httpServletRequest.getSession().setAttribute("vrifyCode", createText);
			log.info("验证码值:" + httpServletRequest.getSession().getAttribute("vrifyCode"));
			// 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
			BufferedImage challenge = captchaProducer.createImage(createText);
			ImageIO.write(challenge, "jpg", jpegOutputStream);
		} catch (IllegalArgumentException e) {
			httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}

		// 定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
		captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
		httpServletResponse.setHeader("Cache-Control", "no-store");
		httpServletResponse.setHeader("Pragma", "no-cache");
		httpServletResponse.setDateHeader("Expires", 0);
		httpServletResponse.setContentType("image/jpeg");
		ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
		responseOutputStream.write(captchaChallengeAsJpeg);
		responseOutputStream.flush();
		responseOutputStream.close();
	}

当前端的<img>标签指向这个接口时,他就会获取到图片验证码,下面的方法是点击验证码图片,刷新验证码。

<body>
	<p>111</p>
	<img border=0 src="http://localhost:8015/api/defaultKaptcha" id="imageMask" onclick="myReload()" style="cursor: pointer">
</body>
<script>
function myReload() {
    document.getElementById("imageMask").src = document.getElementById("imageMask").src + "?nocache=" + new Date().getTime();
}
</script>

一切准备就绪后,启动项目查看结果:

控制台打印的验证码值:

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值