SpringBoot使⽤Captcha⽣成验证码⽬录
1. 基本结构
2. Kaptcha的依赖
3. 配置SpringBoot
4. 配置Captcha
5. ⼯具类
6. 接⼝以及实现类
7. Controller
8. 前端页⾯的实现
⽰例
1. 基本结构
使⽤Captcha⽣成验证码, 利⽤Redis存储验证码
Redis中的结构为, Key是32位的UUID, Value为Captcha的4位随机字母以及数字的集合
设定Redis过期时间为1min, 即可实现过期验证码的⾃动失效
2. Kaptcha的依赖
基本的依赖这⾥不再叙述, 主要说⼀下要导⼊Captcha的依赖
<!--Kaptcha-->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
所有的依赖如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-instance"
xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wang</groupId>
<artifactId>spring_security_framework</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring_security_framework</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--JDBC-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--SpringSecurity-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!--Thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--Validation-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!--SpringBoot Web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--Mybatis-->
<dependency>
<groupId&batis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!--SpringSecurity with thymeleaf-->
<dependency>
<groupId>as</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>        </dependency>
<!--MySQL connector-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--Lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--Test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<!--Druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.2</version>
</dependency>
<!--FastJSON-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.74</version>
</dependency>
<!--log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--Swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!--HuTool-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.7</version>
</dependency>
<!--Kaptcha-->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3. 配置SpringBoot
配置SpringBoot的配置⽂件, 这⾥主要关注⼀个session的过期时间
#Port
server:
port: 80
servlet:
session:
timeout: 1
spring:
application:
name: SpringSecurityFramework
#dataBase Setting
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/security?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai    driver-class-name: sql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#Druid Setting
druid:
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 30000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
pool-prepared-statements: true
#Setting For Druid StatView and Filter
filters: stat,wall,log4j
max-pool-prepared-statement-per-connection-size: 20
use-global-data-source-stat: true
connection-properties: Sql=true;druid.stat.slowSql
#Redis Setting
redis:
host: 127.0.0.1
port: 6379
#Thymeleaf
thymeleaf:
cache: false
#Mybatis
mybatis:
type-aliases-package: ity
mapper-locations: classpath:Mybatis/mapper/*.xml
configuration:
map-underscore-to-camel-case: true
其余的配置, 如log4j, druid, SpringSecurity, RedisTemplate,这⾥就不再赘述
jquery怎么进行验证
4. 配置Captcha
我们可以通过JAVA的配置类来配置Captcha⽣成验证码的⼀些规则
package com.wang.spring_fig;
le.code.kaptcha.impl.DefaultKaptcha;
le.code.kaptcha.util.Config;
import t.annotation.Bean;
import t.annotation.Configuration;
import java.util.Properties;
/
/Kaptcha配置
@Configuration
public class KaptchaConfig {
@Bean
public DefaultKaptcha producer() {
//Properties类
Properties properties = new Properties();
// 图⽚边框
properties.setProperty("kaptcha.border", "yes");
// 边框颜⾊
properties.setProperty("lor", "105,179,90");
/
/ 字体颜⾊
properties.setProperty("lor", "blue");
// 图⽚宽
properties.setProperty("kaptcha.image.width", "110");
// 图⽚⾼
properties.setProperty("kaptcha.image.height", "40");
// 字体⼤⼩
properties.setProperty("producer.font.size", "30");
// session key
properties.setProperty("kaptcha.session.key", "code");
// 验证码长度
properties.setProperty("producer.char.length", "4");
// 字体
properties.setProperty("producer.font.names", "宋体,楷体,微软雅⿊");
//图⽚⼲扰
properties.setProperty("ise.impl","de.kaptcha.impl.DefaultNoise");
//Kaptcha 使⽤上述配置
Config config = new Config(properties);
//DefaultKaptcha对象使⽤上述配置, 并返回这个Bean
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
5. ⼯具类
使⽤UUID作为key, 同时考虑到对验证码的输出结果可能有不同的要求, 这⾥写两个⼯具类来处理它们UUIDUtil
package com.wang.spring_security_framework.util;
import t.annotation.Bean;
import org.springframework.stereotype.Component;
import java.util.UUID;
@Component public class UUIDUtil {
/** * ⽣成32位的随机UUID * @return 字符形式的⼩写UUID */
@Bean public String getUUID32() {
return UUID.randomUUID().toString() .replace("-", "").toLowerCase();
}
}
CaptchaUtil
package com.wang.spring_security_framework.util;
le.code.kaptcha.impl.DefaultKaptcha;
import com.wang.spring_security_framework.service.CaptchaService;
import dec.base64.Base64Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
@Component
//Captcha ⽣成⼯具
public class CaptchaUtil {
@Autowired
private DefaultKaptcha producer;
@Autowired
private CaptchaService captchaService;
//⽣成catchCreator的map
public Map<String, Object> catchaImgCreator() throws IOException {
//⽣成⽂字验证码
String text = ateText();
//⽣成⽂字对应的图⽚验证码
BufferedImage image = ateImage(text);
//将图⽚写出
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();        ImageIO.write(image, "jpg", outputStream);
//对写出的字节数组进⾏Base64编码 ==> ⽤于传递8⽐特字节码
BASE64Encoder encoder = new BASE64Encoder();
//⽣成token
Map<String, Object> token = ateToken(text);
token.put("img", ByteArray()));
return token;
}
}
6. 接⼝以及实现类
1. 接⼝
package com.wang.spring_security_framework.service;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.Map;
public interface CaptchaService {
//⽣成token
Map<String, Object> createToken(String captcha);
//⽣成captcha验证码
Map<String, Object> captchaCreator() throws IOException;
//验证输⼊的验证码是否正确
String versifyCaptcha (String token, String inputCode);
}
2. 实现类
package com.wang.spring_security_framework.service.serviceImpl;
le.code.kaptcha.impl.DefaultKaptcha;
import com.wang.spring_security_framework.service.CaptchaService; import com.wang.spring_security_framework.util.CaptchaUtil;
import com.wang.spring_security_framework.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.RedisTemplate;
import org.ValueOperations;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import urrent.TimeUnit;
@Service
public class CaptchaServiceImpl implements CaptchaService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private UUIDUtil uuidUtil;
@Autowired
private CaptchaUtil captchaUtil;
//从SpringBoot的配置⽂件中取出过期时间
@Value("${server.servlet.session.timeout}")
private Integer timeout;
//UUID为key, 验证码为Value放在Redis中
@Override

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。