springboot整合thymeleaf,kaptcha实现图片验证码验证例子

kaptcha简介:

Kaptcha 是一个可高度配置的实用验证码生成工具,可自由配置的选项如:

验证码的字体
验证码字体的大小
验证码字体的字体颜色
验证码内容的范围(数字,字母,中文汉字!)
验证码图片的大小,边框,边框粗细,边框颜色
验证码的干扰线
验证码的样式(鱼眼样式、3D、普通模糊、…)

Kaptcha 详细配置表

kaptcha.border图片边框,合法值:yes , noyes
kaptcha.border.color边框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue.black
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

案例解析以及整合

实现案例的过程和流程:
向spring注入配置了我们所需要的验证码的DefaultKaptcha,自动装配的defaultKaptcha,通过servletAPI结合IO流创建验证码,并放进session中。然后使用表单提交映射到校验验证码的方法中判断,正常返回跳转成功页面,失败跳转回首页并且拿到错误消息显示!!!

首先用脚手架创建工程,不重复说了:
然后导入依赖:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>

创建配置类以及controller还有编写相关前端页面,以及导入相关资源
在这里插入图片描述

在这里插入图片描述

package com.tho.config;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Properties;

@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", "red");
		// 图片宽
		properties.setProperty("kaptcha.image.width", "110");
		// 图片高
		properties.setProperty("kaptcha.image.height", "40");
		// 字体大小
		properties.setProperty("kaptcha.textproducer.font.size", "30");
		// session key
		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;
	}
}
package com.tho.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

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;

@Controller
public class KaptchaController {

	/**
	 * 1、验证码工具
	 */
	@Autowired
	DefaultKaptcha defaultKaptcha;
	
	/**
	 * 2、生成验证码
	 * @param httpServletRequest
	 * @param httpServletResponse
	 * @throws Exception
	 */
	@RequestMapping("/defaultKaptcha")
	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("rightCode", 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();
	}

	/**
	 * 3、校对验证码
	 * @param httpServletRequest
	 * @param httpServletResponse
	 * @return
	 */
	@RequestMapping("/imgvrifyControllerDefaultKaptcha")
	public ModelAndView imgvrifyControllerDefaultKaptcha(HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse) {
		ModelAndView andView = new ModelAndView();
		String rightCode = (String) httpServletRequest.getSession().getAttribute("rightCode");
		String tryCode = httpServletRequest.getParameter("tryCode");
		System.out.println("rightCode:"+rightCode+" ———— tryCode:"+tryCode);
		if (!rightCode.equals(tryCode)) {
			andView.addObject("info", "错误的验证码");
			andView.setViewName("index");
		} else {
			andView.addObject("info", "登录成功");
			andView.setViewName("success");
		}
		return andView;
	}
	
	@RequestMapping("/toIndex")
	public String toIndex() {
		return "index";
	}
}

index.html:

<!DOCTYPE html>
<!-- thymeleaf 提示功能 -->
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
    <meta charset="UTF-8"></meta>
    <title>hello</title>
    <!-- 引入BootStrap -->
    <link rel="stylesheet" href="../bootstrap3/css/bootstrap-theme.min.css" />
    <link rel="stylesheet" href="../bootstrap3/css/bootstrap.min.css" />
    <script type="text/javascript" src="../bootstrap3/js/jquery-1.11.2.min.js"></script>
    <script type="text/javascript" src="../bootstrap3/js/bootstrap.min.js"></script>
</head>
<style type="text/css">
    body {
        padding: 10px
    }
</style>
<body>
<!-- 提示 -->
<h3 th:text="${info}"></h3>
<div>
    <!-- 后面添加参数起到清除缓存作用 -->
    <img alt="验证码" onclick="this.src='/defaultKaptcha?d='+new Date()*1" src="/defaultKaptcha" />
</div>
<form action="imgvrifyControllerDefaultKaptcha" >
    <input type="text" name="tryCode" />
    <input type="submit" value="提交" class="btn btn-success"></input>
</form>
</body>
</html>

success.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"></meta>
    <title>验证成功</title>
</head>
<body>
<h1>验证成功</h1>
</body>
</html>

启动然后访问 localhost:8080
在这里插入图片描述
测试:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述在这里插入图片描述

至此已经完成整合!!!,当然也可以使用jcaptcha,基本包是一样的,有一篇直接不是springmvc的直接,可以参考上面配置小改,基本一致,可供参考地址如下:https://www.cnblogs.com/chuanqi1995/p/11583407.html

当然还有不使用别人工具类。自定义编写的验证码工具实现:https://blog.csdn.net/lp840312696/article/details/90635039

当然也可以使用hutool工具包导入:

 <dependency>
           <groupId>cn.hutool</groupId>
           <artifactId>hutool-captcha</artifactId>
           <version>5.5.0</version>
</dependency>

hutool验证码工具包相关文档:https://hutool.cn/docs/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值