项目场景:
提示:这里简述项目相关背景:
修改若依框架的验证码
问题描述
提示:这里描述项目中遇到的问题:
若依框本身验证码比较丑,换成EasyCaptcha验证码
解决方案:
首先在pom文件中添加依赖
<!-- 自己加的验证码EasyCaptcha依赖 -->
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
<version>1.6.2</version>
</dependency>
然后在CaptchaController类更改
package com.example.admin.common;
import com.example.common.constant.Constants;
import com.example.common.core.domain.AjaxResult;
import com.example.common.core.redis.RedisCache;
import com.example.common.utils.VerifyCodeUtils;
import com.example.common.utils.sign.Base64;
import com.example.common.utils.uuid.IdUtils;
import com.example.web.domain.WebAssInfo;
import com.example.web.domain.WebExpertsScore;
import com.example.web.service.IWebAssInfoService;
import com.example.web.service.IWebExpertsScoreService;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.ChineseCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* 验证码操作处理
*/
@RestController
public class CaptchaController {
@Autowired
private RedisCache redisCache;
@Autowired
private IWebExpertsScoreService webExpertsScoreService;
@Autowired
private IWebAssInfoService webAssInfoService;
// 验证码类型,从配置文件获取
@Value("${review.captchaType}")
private String captchaType;
/**
* 生成验证码
*/
@CrossOrigin
@GetMapping({"/captchaImage"})
public AjaxResult getCode(HttpServletResponse response) throws IOException {
AjaxResult ajax = AjaxResult.success();
// 保存验证码信息
String uuid = IdUtils.simpleUUID();
String verifyKey = "captcha_codes:" + uuid;
//以下是自己新加的代码——————————————————————————————————————————————————————————
//验证码EasyCaptcha工具
Captcha captcha = null;
if ("math".equals(captchaType)) {//math 算术验证
//创建算术验证码
captcha = new ArithmeticCaptcha(115, 42);
} else if ("chinese".equals(captchaType)) {//chinese 中文验证
//中文验证
captcha = new ChineseCaptcha(115, 42);
} else if ("char".equals(captchaType)) {//char 字符验证
//创建字符验证码
captcha = new SpecCaptcha(115,42);
}
//得到验证码的值
String code = captcha.text();
//存入redis
redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
ajax.put("uuid", uuid);
ajax.put("img", captcha.toBase64()); //获得图片的base64编码
return ajax;
}
}