使用SpringBoot+Kaptcha实现图片验证码功能
在用户登录页面,添加图片验证码,实现用户输入正确的验证码才能登录的功能。
验证码的作用:有效防止对某一个特定注册用户用特定程序暴力破解方式,进行不断的登录尝试的问题。
1、在idea中创建SpringBoot项目,打开 pom.xml 文件,添加 Kaptcha 的依赖。
<!-- 验证码 -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>${kaptcha.version}</version>
</dependency>
2、编写 Kaptcha 的配置类,设置生成图片验证码的样式,编码如下:
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", "no");
//字体颜色
properties.setProperty("kaptcha.textproducer.font.color", "blue");
//图片宽
properties.setProperty("kaptcha.image.width", "135");
//图片高
properties.setProperty("kaptcha.image.height", "50");
//使用哪些字符生成验证码
properties.setProperty("kaptcha.textproducer.char.string", "ACEHKTW247");
//字体大小
properties.setP