zoukankan      html  css  js  c++  java
  • Spring中整合Cage,实现验证码功能

    1.pom.xml中添加Cage依赖。

        <dependency>
                <groupId>com.github.cage</groupId>
                <artifactId>cage</artifactId>
                <version>1.0</version>
            </dependency>    

    项目相关资料:https://akiraly.github.io/cage/quickstart.html 。

    2.Controller:@RestController

    
    
    @RestController
    @RequestMapping("captcha")
    public class CaptchaController {

    @Autowired
    private CaptchaService captchaService;

    @RequestMapping("get")
    public void get(HttpServletResponse response,String key) throws IOException {
    response.setContentType("image/jpeg");//设置响应的媒体类型,这样浏览器会识别出响应的是图片
    response.getOutputStream().write(captchaService.getCaptcha(key));
    response.flushBuffer();
    }
    }

    3.Service:

    @Service("captchaService")
    public class CaptchaService {
    
        private static final Logger log = LoggerFactory.getLogger(CaptchaService.class);
    
        @Autowired
        RedisDao redisDao;
        Cage cage = new GCage();
    
        public byte[] getCaptcha(String id) {
            if (StringUtils.isBlank(id)) {
                return null;
            }
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            String token = cage.getTokenGenerator().next().substring(0, 4);
            try {
                cage.draw(token, os);
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            String key = "captcha-" + id;
            redisDao.getJredis().opsForValue().set(key, token);
            redisDao.getJredis().expire(key, 1, TimeUnit.HOURS);
            return os.toByteArray();
        }
    
        public boolean matchCaptcha(String id, String captcha) {
            if (StringUtils.isBlank(id) || StringUtils.isBlank(captcha)) {
                return false;
            }
            String key = "captcha-" + id;
            String redisCaptcha = String.valueOf(redisDao.getJredis().opsForValue().get(key));
            if (StringUtils.isBlank(redisCaptcha)) {
                return false;
            }
            log.info(id + ", " + captcha + ", " + redisCaptcha);
            return StringUtils.equalsIgnoreCase(captcha, redisCaptcha);
        }
    }

    4.前端页面:

    $('#yzmimg').attr('src','https://localhost:8082/captcha/get?key'+timestamp);

    总结:设置

    response.setContentType("image/jpeg"),这样返回时将会以图片形式,此处为坑。
  • 相关阅读:
    javascript中的this指向
    面向对象和面向过程、对象、类、实例
    javascript
    实例011:养兔子
    day13匿名函数
    实例010:给人看的时间
    python基础学习day12 生成器与推导式
    实例009:暂停一秒输出
    python基础学习day11函数的进阶
    第一部分:趣味算法入门;第八题:冒泡排序(并与选择排序对比)
  • 原文地址:https://www.cnblogs.com/zacky31/p/8601633.html
Copyright © 2011-2022 走看看