springboot-整合vue和图片验证码

时光毁灭记忆、已成空白 提交于 2019-12-08 15:42:49

springboot-整合vue和图片验证码

完整代码下载链接:

https://github.com/2010yhh/springBoot-demos/tree/master/springboot-shiro

环境

idea2018,jdk1.8,

springboot版本:springboot1.5.9.RELEASE

chrome浏览器

Kaptcha2.3.2

1.配置

1.1pom

 
  <!-- 仓库:Kaptcha并没有上传到中央仓库,可以从Sonatype Forge仓库获得该构件-->
    <repositories>
        <repository>
            <id>sonatype-forge</id>
            <name>Sonatype Forge</name>
            <url>http://repository.sonatype.org/content/groups/forge/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <!--依赖:Kaptcha是用于生成验证码的开源类库-->
        <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>

1.2Kaptcha的初始化

@Component
public class KaptchaConfig {
   @Bean
   public DefaultKaptcha getDefaultKaptcha() {
      DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
      Properties properties = new Properties();
      // 图片宽
      properties.setProperty("kaptcha.image.width", "180");
      // 图片高
      properties.setProperty("kaptcha.image.height", "50");
      // 图片边框
      properties.setProperty("kaptcha.border", "yes");
      // 边框颜色
      properties.setProperty("kaptcha.border.color", "105,179,90");
      // 字体颜色
      properties.setProperty("kaptcha.textproducer.font.color", "blue");
      // 字体大小
      properties.setProperty("kaptcha.textproducer.font.size", "40");
      // session key
      properties.setProperty("kaptcha.session.key", "code");
      // 验证码长度
      properties.setProperty("kaptcha.textproducer.char.length", "4");
      // 字体
      properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
      Config config = new Config(properties);
      defaultKaptcha.setConfig(config);
      return defaultKaptcha;
   }
}

1.3Kaptcha生产验证码

@RequestMapping("/createImageCode")
public void createImageCode(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
   byte[] captchaChallengeAsJpeg = null;
   ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
   try {
      // 生产验证码字符串并保存到session中
      String createText = defaultKaptcha.createText();
      request.getSession().setAttribute("imageCode", createText);
      // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
      BufferedImage challenge = defaultKaptcha.createImage(createText);
      ImageIO.write(challenge, "jpg", jpegOutputStream);
      logger.info("createImageCode:{}",request.getSession().getAttribute("imageCode"));
   } catch (IllegalArgumentException e) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
   }

   // 定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
   captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
   response.setHeader("Cache-Control", "no-store");
   response.setHeader("Pragma", "no-cache");
   response.setDateHeader("Expires", 0);
   response.setContentType("image/jpeg");
   ServletOutputStream responseOutputStream = response.getOutputStream();
   responseOutputStream.write(captchaChallengeAsJpeg);
   responseOutputStream.flush();
   responseOutputStream.close();
}

1.4vue前端代码

 <el-form :model="form" label-width="120px" :rules="rules">
            <el-form-item label="用户名" required>
                <el-input v-model="form.userName" auto-complete="off" class="el-col-width" required></el-input>
            </el-form-item>
            <el-form-item label="密码" required>
                <el-input type="password" v-model="form.passWord" auto-complete="off" class="el-col-width" required></el-input>
            </el-form-item>
            <!-- <el-form-item>
              <el-checkbox v-model="form.rememberMe">下次自动登录</el-checkbox>
            </el-form-item> -->
            <el-form-item label="输入验证码" required>
                <el-input v-model="form.inputImageCode" auto-complete="off" class="el-col-width"></el-input>
            </el-form-item>
            <el-form-item required>
                <img id="img" alt="验证码" onclick="this.src='/createImageCode?d='+new Date()*1" src="/createImageCode" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSubmit">登录</el-button>
            </el-form-item>
        </el-form>
 handleSubmit() {
      var params = {}
      params.userName = this.form.userName
      params.passWord = this.form.passWord
      params.rememberMe = this.form.rememberMe
      params.inputImageCode = this.form.inputImageCode
      HTTP.checkImageCode(params).then(r => {
        //先校验输入的验证码
        if (r.data.code === '200') {
          HTTP.login(params).then(r => {
            //后台定义的状态码,登录成功后跳转
            if (r.data.code === '200') {
              this.$router.push({ name: 'home', params: { user: r.data.user } })
              this.$notify({
                title: 'success',
                message: '登录成功',
                type: 'success',
                position: 'bottom-right'
              })
            } else {
                document.getElementById("img").src="/createImageCode?d='+new Date()*1"; //这里的图片是更换后的图片
              this.$notify.error({
                title: 'error',
                message: '登录失败:' + r.data.msg,
                type: 'error',
                position: 'bottom-right'
              })
            }
          })
        } else {
            document.getElementById("img").src="/createImageCode?d='+new Date()*1"; //这里的图片是更换后的图片
          this.$notify.error({
            title: 'error',
            message: '验证码错误',
            type: 'error',
            position: 'bottom-right'
          })
        }
      })
    }

2.测试

2.1本地web测试

http://localhost:8090
结果:输入正确信息可以正常登录
在这里插入图片描述

在这里插入图片描述

2.2验证码的刷新

验证码错误或者输入信息错误会或者点击了验证码:验证码会自动刷新
在这里插入图片描述

在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!