本部分代码来源于牛客网官方的仿牛客论坛项目,仅供个人学习和探讨使用。
文章目录生成验证码部分
相关类库:
1. 导入jar包2. 编写 kaptcha 配置类3. 编写controller层4. 测试5. 前端代码编辑
相关类库:kaptcha
基本思路:
- 导入jar包编写kaptcha配置类随机生成字符、图片
- 访问 https://mvnrepository.com/ , 搜索 kaptcha , 复制相关代码。具体操作如下。
(当然,有可能网站无法访问,那就直接复制我下面给的代码到 pom.xml 中就好了)
com.github.penggle kaptcha 2.3.2
1.1 打开网站后,点击第一个
1.2 点击划线区域进入
1.3 复制相关代码,粘贴到 pom.xml 中
说明:复制后要更改 package 包名。
package com.zcq.community.config;
import com.google.code.kaptcha.Producer;
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
public Producer kaptchaProducer() {
Properties properties = new Properties();
// 1. 配置相关参数
properties.setProperty("kaptcha.image.width", "100"); // 宽度
properties.setProperty("kaptcha.image.heigth", "40"); // 高度
properties.setProperty("kaptcha.textproducer.font.size", "32");
properties.setProperty("kaptcha.textproducer.font.color", "0,0,0");
properties.setProperty("kaptcha.textproducer.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
properties.setProperty("kaptcha.textproducer.char.length", "4");
properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");
DefaultKaptcha kaptcha = new DefaultKaptcha();
Config config = new Config(properties);
kaptcha.setConfig(config);
return kaptcha;
}
}
3. 编写controller层
在controller类中添加路径配置,并完成前后端交互业务逻辑
package com.zcq.community.controller;
import com.google.code.kaptcha.Producer;
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.RequestMethod;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
@Controller
public class TestController {
@Autowired
private Producer kaptchaProducer;
@RequestMapping(path = "/kaptcha", method = RequestMethod.GET)
public void getKaptcha(HttpServletResponse response, HttpSession session) {
// 生成验证码
String text = kaptchaProducer.createText();
BufferedImage image = kaptchaProducer.createImage(text);
// 将验证码存入session
session.setAttribute("kaptcha", text);
// 将图片输出给浏览器
response.setContentType("image/png");
try {
OutputStream os = response.getOutputStream();
ImageIO.write(image, "png", os);
} catch(IOException e) {
e.printStackTrace();
// 后期改成日志形式体现
// logger.error("相应验证码失败: " + e.getMessage());
}
}
}
4. 测试
说明:我的本单元测试路径为 localhost:8080/community/kaptcha
点击左上角刷新按钮会有不同的结果出来。
考虑到业务逻辑,现实中应该有个 刷新验证码 字样的按钮。
最后,重新启动项目,刷新网站即可。



