赞
踩
目录
EasyCaptcha,Java图形验证码,支持gif、中文、算术等类型,可用于Java Web、JavaSE等项目。
- <!-- 验证码 -->
- <dependencies>
- <dependency>
- <groupId>com.github.whvcse</groupId>
- <artifactId>easy-captcha</artifactId>
- <version>1.6.2</version>
- </dependency>
- </dependencies>
前后端分离项目建议不要存储在session中,存储在redis中,redis存储需要一个key,key一同返回给前端用于验证输入
- @Controller
- public class CaptchaController {
- @Autowired
- private RedisUtil redisUtil;
-
- @ResponseBody
- @RequestMapping("/captcha")
- public JsonResult captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
- //动态验证码
- GifCaptcha gifCaptcha = new GifCaptcha(130,48,4);
- //静态验证码
- SpecCaptcha specCaptcha = new SpecCaptcha(130,48,4);
- //中文验证码
- ChineseCaptcha chineseCaptchaAbstract = new ChineseCaptcha(130,28,4);
- //算术验证码
- ArithmeticCaptcha arithmeticCaptcha = new ArithmeticCaptcha(130 , 28 , 4);
-
- String verCode = specCaptcha.text().toLowerCase();
- String key = UUID.randomUUID().toString();
- // 存入redis并设置过期时间为30分钟
- redisUtil.setEx(key, verCode, 30, TimeUnit.MINUTES);
- // 将key和base64返回给前端
- return JsonResult.ok().put("key", key).put("image", specCaptcha.toBase64());
- }
-
- @ResponseBody
- @PostMapping("/login")
- public JsonResult login(String username,String password,String verCode,String verKey){
- // 获取redis中的验证码
- String redisCode = redisUtil.get(verKey);
- // 判断验证码
- if (verCode==null || !redisCode.equals(verCode.trim().toLowerCase())) {
- return JsonResult.error("验证码不正确");
- }
- }
- }
- <img id="verImg" width="130px" height="48px"/>
-
- <script>
- var verKey;
- // 获取验证码
- $.get('/captcha', function(res) {
- verKey = res.key;
- $('#verImg').attr('src', res.image);
- },'json');
-
- // 登录
- $.post('/login', {
- verKey: verKey,
- verCode: '8u6h',
- username: 'admin',
- password: 'admin'
- }, function(res) {
- console.log(res);
- }, 'json');
- </script>



Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。