废话不多说上代码,Ctrl+C 然后Ctrl+V 自己改吧改吧就阔以了。
1、maven方式引入
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
<version>1.6.2</version>
</dependency>
2、项目中使用
控制层使用信息
@Controller
public class userController {
......
@GetMapping("/validateCode")
public void validateCode(HttpServletRequest request, HttpServletResponse response) throws ScriptException, IOException {
response.setHeader("Cache-Control", "no-cache");
//算术验证码生成
ArithmeticCaptcha arithmeticCaptcha = userService.checkResult();
// 获取运算的公式:3+2*7=? 这里的结果不会为负数
String verifyCode = arithmeticCaptcha.getArithmeticString();
log.info("validateCode1:"+verifyCode);
Session session = SecurityUtils.getSubject().getSession();
session.removeAttribute("validateCode");
session.setAttribute("validateCode", arithmeticCaptcha.text());
response.setContentType("image/jpeg");
arithmeticCaptcha.out(response.getOutputStream());
}
}
业务层信息
/**校验计算公式结果
* @return
* @author nicai
*/
public static ArithmeticCaptcha checkResult() throws ScriptException {
//生成算术验证码
ArithmeticCaptcha arithmeticCaptcha= new ArithmeticCaptcha(140 , 30);
arithmeticCaptcha.setLen(3); // 几位数运算,默认是两位
//计算结果
int sum = Integer.parseInt(arithmeticCaptcha.text());
if (sum < 0) {
//算术验证码
ArithmeticCaptcha arithmeticCaptcha1 = new ArithmeticCaptcha(140 , 30);
arithmeticCaptcha1.setLen(3); // 几位数运算,默认是两位
return checkResult();
}
return arithmeticCaptcha;
}
3、前端请求、或者Postman请求
路径:127.0.0.1:8080/tsenglish/user/validateCode(IP和端口号选自己的)
返回结果:
总结: 这玩楞真好用,代码不用写那么多,还简单。总结后感觉就俩字:“啊,真香!”。