版权声明:本文为 小异常 原创文章,非商用自由转载-保持署名-注明出处,谢谢!
本文网址:https://sunkuan.blog.csdn.net/article/details/108080646
本篇博客主要总结 Spring Boot 整合 Kaptcha 来实现图片验证码。本篇会以一个 Demo 为例,以 Spring Boot 为基础架构,不涉及任何有关数据库的操作以及前端炫酷界面的实现,方便初学者学习整理。
<dependency>
<groupId>com.github.pengglegroupId>
<artifactId>kaptchaartifactId>
<version>2.3.2version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title heretitle>
head>
<body>
<form action="/login" method="post">
<input type="text" name="code"><img src="/code">
<input type="submit" value="提交">
form>
body>
html>
/**
* 验证码 工具类
* @author SunKuan
* @create 2020-8-17 14:21:1
*/
public class CodeUtil {
/**
* 验证码校验
* @param request
* @return
*/
public static boolean checkVerifyCode(HttpSession session, String key) {
// 获取生成的验证码
String verifyCode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
System.out.println("verifyCode: " + verifyCode);
// 获取用户输入的验证码
if (key == null || !key.equals(verifyCode)) {
return false;
}
return true;
}
}
# 项目配置
server:
port: 8888
# Spring 配置
spring:
# Thymeleaf 配置
thymeleaf:
prefix: classpath:/templates/
suffix: .html
cache: false
# 验证码配置
kaptcha:
border: "no" # 是否有边框,默认为 yes,可选 yes、no
border.color: 105,179,90 # 边框颜色
textproducer:
font:
color: blue # 验证码字体颜色
size: 30 # 文本字符大小
names: 宋体,楷体 # 文本字体样式
char:
length: 4 # 验证码文本字符长度
image:
width: 120 # 图片宽度
height: 40 # 图片高度
session:
key: code # 存储 session key
/**
* Kaptcha配置类
* 用于生成图形验证码
* @author SunKuan
* @create 2020-8-17 11:48:57
*/
@Configuration
public class KaptchaConfig {
/**
* 边框
*/
@Value("${kaptcha.border}")
private String border;
/**
* 边框颜色
*/
@Value("${kaptcha.border.color}")
private String borderColor;
/**
* 字体颜色
*/
@Value("${kaptcha.textproducer.font.color}")
private String textproducerFontColor;
/**
* 字体大小
*/
@Value("${kaptcha.textproducer.font.size}")
private String textproducerFontSize;
/**
* 字体样式
*/
@Value("${kaptcha.textproducer.font.names}")
private String textproducerFontNames;
/**
* 验证码长度
*/
@Value("${kaptcha.textproducer.char.length}")
private String textproducerCharLength;
/**
* 图片宽度
*/
@Value("${kaptcha.image.width}")
private String imageWidth;
/**
* 图片高度
*/
@Value("${kaptcha.image.height}")
private String imageHeight;
/**
* 存储的 Session Key
*/
@Value("${kaptcha.session.key}")
private String sessionKey;
/**
* 配置 Kapcha 参数
* @return
*/
@Bean
public DefaultKaptcha getDefaultKapcha() {
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
Properties properties = new Properties();
properties.setProperty("kaptcha.border", border);
properties.setProperty("kaptcha.border.color", borderColor);
properties.setProperty("kaptcha.textproducer.font.color", textproducerFontColor);
properties.setProperty("kaptcha.textproducer.font.size", textproducerFontSize);
properties.setProperty("kaptcha.textproducer.font.names", textproducerFontNames);
properties.setProperty("kaptcha.textproducer.char.length", textproducerCharLength);
properties.setProperty("kaptcha.image.width", imageWidth);
properties.setProperty("kaptcha.image.height", imageHeight);
properties.setProperty("kaptcha.session.key", sessionKey);
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
/**
* 图片 控制器
* @author SunKuan
* @create 2020-8-17 11:58:12
*/
@Controller
public class ImgController {
/**
* Kaptcha 配置
*/
@Autowired
private DefaultKaptcha defaultKaptcha;
/**
* 跳转到验证码页面
* @return
*/
@GetMapping("/codeHtml")
public String code() {
return "code";
}
/**
* 验证码
* @return
* @throws IOException
*/
@GetMapping("/code")
public void defaultKaptcha(HttpSession session, HttpServletResponse response) {
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
response.setHeader("Pragma", "no-cache");
response.setContentType("image/jpeg");
// 生成验证码字符串并保存到 session 中
String capText = defaultKaptcha.createText();
System.out.println("capText: " + capText);
session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
// 向客户端写出
BufferedImage bi = defaultKaptcha.createImage(capText);
ServletOutputStream out = null;
try {
out = response.getOutputStream();
ImageIO.write(bi, "jpg", out);
out.flush();
} catch (IOException e) {
System.err.println("输出图形验证码失败");
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 测试验证码是否正确
* @param session
* @param code
* @return
*/
@ResponseBody
@PostMapping("/login")
public String login(HttpSession session, String code) {
System.out.println("code: " + code);
if (!CodeUtil.checkVerifyCode(session, code)) {
return "验证码错误!";
} else {
return "验证码正确!";
}
}
}
本篇博客的源代码我已上传到 CSDN 上,请有需要的小伙伴进行下载。
链接:https://download.csdn.net/download/sun8112133/12721606