1. 介绍与使用
1.1 Kapcha是什么
Kaptcha 是一个Google开源、可自由配置的图片验证码生成工具,可以根据属性来设置自己想要的基本意义上的验证码
对于前端
和后端
后端:
- 随机生成四位数字的验证码图片和数字
- 结合随机生成的UUID作为Key,验证码值作为Value保存验证码到Redis中
- 将UUID和验证码图片响应给用户,等用户提交后验证校验码是否有效
前端:
- 进入登录/注册页面时,获取验证码图片
- 对用户输入的验证码进行简单的规则校验
- 返回登录结果
- 提供刷新验证码的动作,防止出现用户难以辨识的识别码
1.2 基本使用步骤
- 导入POM依赖
- 定义生成验证码图片时的一系列参数:图片的宽高、字符内容、干扰类型等
- 调用com.google.code.kaptcha.impl.DefaultKaptcha#createText()创建验证码值
- 调用com.google.code.kaptcha.impl.DefaultKaptcha#createText(kaptchaText)创建验证图片(BufferedImage)
- 将图片BufferedImage转换为目标
2. SpringBoot集成创建验证码工具
2.1 导入依赖
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
2.2 验证码的配置 KaptchaConfig
对于kaptcha来说,它是图片验证码,因此要配置图片的基本参数:
- 首先,它本质是一张图片,所以将会涉及图片的边框、宽高、背景颜色
- 验证码是字符,这将会涉及到字体类型、字体大小、字体颜色、字体间距、字体数量
- 验证码的另一个重要功能是干扰,这将会涉及干扰类型、干扰样式(干扰的意思是要存在一些阻碍让用户看的不方便)
/**
* 验证码的配置
*/
@Configuration
public class KaptchaConfig {
@Bean
public DefaultKaptcha getDefaultKaptcha(){
//创建一个验证码的实例
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
//创建属性的实例
Properties properties = new Properties();
//设置属性
//设置边框
properties.setProperty("kaptcha.border","no");
/*//设置边框的颜色
properties.setProperty("kaptcha.border.color","white");*/
//设置背景颜色
//背景颜色渐变开始
properties.setProperty("kaptcha.background.clear.from","white");
//背景颜色渐变结束
properties.setProperty("kaptcha.background.clear.to","white");
//字体颜色
properties.setProperty("kaptcha.textproducer.font.color","blue");
//文字间隔
properties.setProperty("kaptcha.textproducer.char.space","10");
//设置验证码的长度
properties.setProperty("kaptcha.textproducer.char.length","4");
//设置图片的宽度
properties.setProperty("kaptcha.image.width","130");
//设置图片的高度
properties.setProperty("kaptcha.image.height","50");
//设置字体样式
properties.setProperty("kaptcha.textproducer.font.names","宋体");
//设置字符串,验证码就是从这里面产生
properties.setProperty("kaptcha.textproducer.char.string","0123456789abcdefghijklmn");
//设置干扰线
properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");
//设置字体大小
properties.setProperty("kaptcha.textproducer.font.size","35");
//将properties包装到配置中
Config config = new Config(properties);
//将配置设置到创建的验证码实例defaultKaptcha
defaultKaptcha.setConfig(config);
//返回
return defaultKaptcha;
}
}
2.3 验证码生成管理器 KaptchaProducerController
@RestController
public class KaptchaProduceController {
//首先将验证码工具导入
@Autowired
DefaultKaptcha defaultKaptcha;
/**
* 生成验证码
*
* @param request
* @param response
* @throws Exception
*/
@GetMapping("/kaptcha")
public void getKaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
//设置响应头
//设置响应头中的Cache-Control字段为no-cache,告诉浏览器不要缓存响应内容。
response.setHeader("Cache-Control", "no-cache");
//用于将“Pragma”HTTP响应标头的值设置为“无缓存”,“Pragma”标头由服务器用于指定客户端或中间代理中的缓存机制的指令。
response.setHeader("Pragma", "no-cache");
//设置响应内容类型为JPEG图像
response.setContentType("image/jpeg");
//创建验证码
String text = defaultKaptcha.createText();
HttpSession session = request.getSession();
//将验证码存入session
session.setAttribute("rightcode", text);
//创建验证码图片,BufferedImage可以用于生成图像
BufferedImage image = defaultKaptcha.createImage(text);
//创建一个响应输出流
ServletOutputStream os = response.getOutputStream();
//将生成的图像写入响应输出流中
ImageIO.write(image, "jpg", os);
//而不会引发任何异常。如果指定的对象为null或在关闭它时发生异常,
// 则该方法将忽略它并继续执行,而不会引发任何进一步的异常。
IOUtils.closeQuietly(os);
}
}
2.4 登录进行验证
/**
* 登录控制器
* ------李硕
*/
@Slf4j
@Controller
public class LoginController {
@Resource
UserService userService;
/**
*
* @param username 账户
* @param password 密码
* @param trycode 验证码
* @param session 储存对象
* @return
*/
@RequestMapping(value = "/user/login")
public ModelAndView login(@RequestParam("username") String username,
@RequestParam("password") String password,
@RequestParam("tryCode") String trycode,
HttpSession session){
ModelAndView modelAndView = new ModelAndView();
//获取session中存储的trycode对象
String rightcode= (String) session.getAttribute("rightcode");
//userService.Login()方法是我创建的一个在数据库搜索数据的一个方法
//搜索数据库中的数据,看是否存在所登录用户的信息
Userbean userbean = userService.Login(username, password);
//打印输出对象
log.info("username:{}",username);
log.info("password:{}",password);
log.info("code:{}",trycode);
if (userbean!=null && rightcode.equals(trycode)) {
modelAndView.setViewName("shopping.html");
return modelAndView;
}
else{
modelAndView.addObject("msg","用户名或密码或验证码有误");
modelAndView.setViewName("login.html");
return modelAndView;
}
}
}
2.5 html页面以及函数调用(注意thymeleaf语法)
把这一部分放在验证码输入框后面
<span>
<input type="text" id="code" name="tryCode" placeholder="VerfiCode">
<img alt="验证码" onclick="this.src='/kaptcha?d='+new Date()*1" th:src="@{./kaptcha}"/>
</span>