1.SpringBoot中集成kaptcha
<!-- 引入图形验证码依赖 -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
2.编写kaptcha配置类KaptchaConfig
package com.sanxia.config;
import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
//kaptcha配置类
@Component
public class KaptchaConfig {
@Bean
public DefaultKaptcha getDefaultKaptcha() {
com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha();
Properties properties = new Properties();
// 图片边框
properties.setProperty("kaptcha.border", "yes");
// 边框颜色
properties.setProperty("kaptcha.border.color", "105,179,90");
// 字体颜色
properties.setProperty("kaptcha.textproducer.font.color", "red");
// 图片宽
properties.setProperty("kaptcha.image.width", "135");
// 图片高
properties.setProperty("kaptcha.image.height", "50");
//使用哪些字符生成验证码
properties.setProperty("kaptcha.textproducer.char.string", "ACEHKTW247");
// 字体大小
properties.setProperty("kaptcha.textproducer.font.size", "43");
// session key
properties.setProperty("kaptcha.session.key", "code");
// 验证码长度
properties.setProperty("kaptcha.textproducer.char.length", "4");
// 字体
properties.setProperty("kaptcha.textproducer.font.names", "Arial");
//干扰线颜色
properties.setProperty("kaptcha.noise.color", "red");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
3.编写kaptcha的控制层代码KaptchaController
3.1.生成验证码接口为"/kaptcha/create",请求方式为get,校验验证码接口为"/kaptcha/check",传递参数为"picCode",请求方式为post
package com.sanxia.controller;
import com.google.code.kaptcha.impl.DefaultKaptcha;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import org.apache.commons.lang3.StringUtils;
import com.sanxia.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
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.ByteArrayOutputStream;
//谷歌的图形验证码模块,使用参考网站https://zhuanlan.zhihu.com/p/68068636
//kaptcha,控制层代码实现
//@Api(tags = {"Google-kaptcha验证码"})
@RestController
@RequestMapping("/kaptcha")
public class KaptchaController {
@Autowired
DefaultKaptcha defaultKaptcha;
// @ApiOperation(value = "生成验证码")
@GetMapping("/create")
public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws Exception {
byte[] captchaChallengeAsJpeg = null;
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
try {
// 生产验证码字符串并保存到session中
String createText = defaultKaptcha.createText();
httpServletRequest.getSession().setAttribute("picCode", createText);
// 使用生成的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
BufferedImage challenge = defaultKaptcha.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();
}
// @ApiOperation(value = "校对验证码")
@PostMapping("/check")
public Result checkVerificationCode(@RequestParam String picCode, HttpServletRequest httpServletRequest) {
String verificationCodeIn = (String)httpServletRequest.getSession().getAttribute("picCode");
httpServletRequest.getSession().removeAttribute("picCode");
if ((StringUtils.isEmpty(verificationCodeIn)) || (!verificationCodeIn.equals(picCode))) {
return Result.fail("验证码错误,或已失效");
} else {
return Result.success(200, "验证码输入正确,校验通过", "");
}
}
}
4.前端HTML代码
<div>
<img id="verificationCodeImg" src="http://localhost:8080/kaptcha/create" style="cursor: pointer;" title="点击生成图形验证码" />
</div>
<script type="text/javascript" >
$(function () {
// 刷新验证码
$("#verificationCodeImg").bind("click", function () {
$(this).hide().attr('src', 'http://localhost:8080/kaptcha/create?').fadeIn();
});
});
</script>
5.试验
5.1.生成验证码
5.2.校验验证码
5.2.1.正确输入
5.2.2.错误输入