掘金 后端 ( ) • 2024-04-21 16:29

theme: channing-cyan highlight: androidstudio

背景:记录一下学习 ruoyi 项目的过程、项目地址

本文主要有以下内容:

  • 若以分离版环境搭建以及项目运行
  • 登录验证码逻辑

前置条件:操作系统为 macos

  • 已本地安装 mysql8
  • Java11
  • Node 20.9
  • git

项目运行

项目下载,通过git clone [email protected]:y_project/RuoYi-Vue.git命令下载项目,项目下载后通过idea打开、由于本操作系统是macos,因此需要修改这三个配置文件。

  • application.yml
  • application.druid.yml
  • logback.xml

application.yml: 文件中的端口号,这一步是可选的,不想与本地其他项目冲突故而修改。除此之外需要修改profile配置项,这一步是为了保证图片上传功能能够正常使用,需要保证配置的目录具有可读可写的权限

application-druid.yml: 需要把连接信息修改为本地。数据库相关的文件在项目的sql文件夹下,按照文档执行即可。

logback.xml: 这一步是修改日志的保存目录,也需要保证该目录具有可读可写的权限。

修改完如上配置文件之后,即可启动后端项目。

前端项目:进入到 ruo-ui 目录下,通过shell终端执行 npm install,命令执行完毕后通过 vscode 打开,修改 vue-config.js 文件

修改 target 中的端口号为后端项目启动的端口号,如果之前没改则不需要!

此时通过 npm run dev 即可启动项目。

图片验证码功能实现

application.yml 文件中的 ruoyi.captchaType:math 这一个配置项就是配置了图片验证码验证方式。

图片验证码的后端接口在 ruoyi-admin/com/ruoyi/web/controller/CaptchaController.java 类中

 @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException
    {
        // 1.创建返回对象
        AjaxResult ajax = AjaxResult.success();
       // 2.获取是否开启验证、先在redis中找、然后去库sys_config里面找默认开启、最后在设置到redis中
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled)
        {
            return ajax;
        }
​
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
​
        String capStr = null, code = null;
        BufferedImage image = null;
​
        // 生成验证码
        String captchaType = RuoYiConfig.getCaptchaType();
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }
        // 保存用户的验证登录信息到redis中
        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return AjaxResult.error(e.getMessage());
        }
​
        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }

以上便是 ruoyi 分离版项目运行配置以及登录验证的过程分析。