1、添加pom依赖
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、配置redis的yaml文件
redis:
host: ip地址
port: 6379(一般使用该端口)
password: 密码(最好拿引号括起来)
jedis:
pool:
max-active: 8
max-wait: -1
max-idle: 500
min-idle: 0
lettuce:
shutdown-timeout: 30000
3、编写config文件
package com.twogroup.shoppingwall.config;
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(value = "DefaultKaptcha")
public DefaultKaptcha getDefaultKaptcha(){
DefaultKaptcha captchaProducer = 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", "blue");
properties.setProperty("kaptcha.image.width", "110");
properties.setProperty("kaptcha.image.height", "40");
properties.setProperty("kaptcha.textproducer.font.size", "30");
properties.setProperty("kaptcha.session.key", "code");
properties.setProperty("kaptcha.textproducer.char.length", "4");
properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
Config config = new Config(properties);
captchaProducer.setConfig(config);
return captchaProducer;
}
}
4、编写验证码的util类
package com.twogroup.shoppingwall.util;
import javax.servlet.http.HttpServletRequest;
public class CodeUtil {
public static String getString(HttpServletRequest request, String key) {
try {
String result = request.getParameter(key);
if(result != null) {
result = result.trim();
}
if("".equals(result)) {
result = null;
}
return result;
}catch(Exception e) {
return null;
}
}
public static boolean checkVerifyCode(HttpServletRequest request,String code,Object email) {
String verifyCodeExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
RedisUtil redisUtil = new RedisUtil();
Object redis = redisUtil.getRedis(email );
if(code == null ||!code.equals(redis)) {
Result.fail("验证码错误");
return false;
}
return true;
}
}
5、编写redis的util类
package com.twogroup.shoppingwall.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
public class RedisUtil {
@Resource
private RedisTemplate<String, Object> redisTemplate;
public boolean setRedis(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public Object getRedis(Object key){
System.out.println("key:---->"+redisTemplate.opsForValue().get(key));
return key == null ? null : redisTemplate.opsForValue().get(key);
}
public boolean setRedis(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
setRedis(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().decrement(key, delta);
}
}
6、编写验证码的controller类
package com.twogroup.shoppingwall.controller;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.twogroup.shoppingwall.util.RedisUtil;
import com.twogroup.shoppingwall.util.Result;
import com.twogroup.shoppingwall.util.UserUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
@Controller
@Api(tags = "A:生成图片验证码的controller")
public class CodeController {
@Autowired
private Producer captchaProducer = null;
private RedisUtil redisUtil = new RedisUtil();
@GetMapping("/kaptch")
public void getKaptchaImage(String email,HttpServletRequest request, HttpServletResponse response) throws Exception {
if(!UserUtil.emailUtil(email)){
Result.fail("邮箱格式错误");
return;
}
HttpSession session = request.getSession();
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
response.setHeader("Pragma", "no-cache");
response.setContentType("image/jpeg");
String capText = captchaProducer.createText();
session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
session.setAttribute(email,email);
session.getAttribute(email);
redisUtil.setRedis(email,capText,60);
Object redis = redisUtil.getRedis(email);
System.out.println("验证码:"+redis);
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
}
}
7、验证图片验证码与用户输入的是否正确
@GetMapping("/loginByPassword")
public Result loginByPassword(String email, String password,HttpServletResponse response,HttpServletRequest request,String code){
HttpSession session = request.getSession();
Object attribute = session.getAttribute(email);
if(!CodeUtil.checkVerifyCode(request,code,attribute)){
return Result.fail("验证码有误!");
}
return Result..sucess("成功");
}