• 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"),这样返回时将会以图片形式,此处为坑。
  • 相关阅读:
    PKUSC2021游记
    P3349 [ZJOI2016]小星星
    序二
    1.3 解析库的安装
    1.2 请求库的安装
    1.5 存储库的安装
    1.6 Web 库的安装
    1.7 App 爬取相关库的安装
    2.1 HTTP 基本原理
    1.9 部署相关库的安装
  • 原文地址:https://www.cnblogs.com/zacky31/p/8601633.html
Copyright © 2020-2023  润新知